【发布时间】:2012-11-18 20:50:34
【问题描述】:
我有以下标记,其中包含 10 个 pre 元素,类为 indent:
<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,你会得到更好的调试数据。 -
$.each(".indent") 不会对 .indent 对象进行交互。它在“.indent”字符串上进行交互。
-
只是一个旁注:最好使用console.log而不是alert。更适合测试,关闭所有这些弹出窗口很痛苦。
-
@luschn 谢谢,早期版本确实使用了
console.log(),但经过数小时的挠头和双重猜测,必须更改每一位代码以防万一:P
标签: javascript iteration jquery