0
<ul>
  <li> <div class="time"> at 2011-02-05 17:44:28</div></li>
  <li> <div class="time"> at 2011-02-05 17:40:20</div></li>
  <li> <div class="time"> at 2011-02-05 17:15:11</div></li>
  <li> <div class="time"> at 2011-02-05 17:04:14</div></li>
  <li> <div class="time"> at 2011-02-05 15:54:56</div></li>
</ul>

//Reformat timeStamps
var timeIndex = 0;
while (timeIndex < 51)
{
  var timeIndexHTML = document.getElementsByClassName("time")[timeIndex].innerHTML;
  timeIndexHTML = "Reformatted time";
  document.getElementsByClassName("time")[timeIndex].innerHTML = timeIndexHTML;
  timeIndex++;
}

如何检测类的最后一个元素,然后将 51 设为变量?

//
//*****************************EDITS HERE**************************************
//
//Example:
  var LAST_ELEMENT_OF_CLASS = someMagicCode("time");

进而

while (timeIndex < LAST_ELEMENT_OF_CLASS +1){...}

请注意,它目前不起作用,因为它试图评估

document.getElementsByClassName("time")[5]

哪个不存在

4

1 回答 1

4

让我猜猜。你想要的是这样的:

var elems = document.getElementsByClassName("time");
for(var timeIndex = 0; timeIndex < elems.length; ++timeIndex)
{
  elems[timeIndex].innerHTML = "Reformatted time";
}

(如果这不是你想要的,请澄清问题)

于 2011-02-06T02:36:24.100 回答