我有以下标记,其中包含10个类名为indent
的pre
元素:
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
<pre class="indent"></pre>
我正在使用以下 jQuery .each()
函数来迭代遍历每个元素:
$(function(){
$.each(".indent", function(index){
alert(index);
});
});
我希望看到10个警报,但是我只看到了7个。
然而,使用 $(".indent").each()
可以按预期工作:
$(function(){
$(".indent").each(function(index){
alert(index);
});
});
查看$.each()
的文档,我明白它们之间有所不同:
$.each()
函数与$(selector).each()不同,后者仅用于遍历jQuery对象。
但我不明白为什么在这种情况下它不能遍历所有元素。
这是为什么?
console.log
代替alert
,能够获得更好的调试数据。 - zzzzBovconsole.log()
,但经过数小时的苦思冥想和反复确认,每一行代码都必须更改以防万一 :P - Curtis