54

我有以下标记,其中包含 10 个pre元素的类indent

​&lt;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 对象。

但我不明白为什么在这种情况下,它不会遍历所有元素。

为什么会这样?

4

3 回答 3

145
$.each(".indent", function(index){

不会遍历长度为 7 个字符$('.indent')的字符串,而是遍历其中的元素。".indent"

参考


基于jQuery源代码的更详细的解释:

jQuery 首先检查第一个参数obj(这里是你的字符串)是否有length

var ...
        length = obj.length,
        isObj = length === undefined || jQuery.isFunction( obj );

你的字符串有一个length(而不是一个函数),isObjfalse.

在这种情况下,将执行以下代码:

for ( ; i < length; ) {
    if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
        break;
    }
}

所以,给定函数f,下面的代码

$.each(".indent", f);

相当于

for (var i=0; i<".indent".length; i++) {
    var letter = ".indent"[i];
    f.call(letter, i, letter);
}

(您可以记录使用的字母或提醒使用var f = function(i,v){console.log(v)};的微妙之处之一)callvar f = function(){console.log(this)};

于 2012-11-30T15:51:45.920 回答
38

您正在遍历字符串,您应该将对象或数组传递给$.each方法:

$(function(){    
    $.each($(".indent"), function(index){
       alert(index);
    });    
});
于 2012-11-30T15:52:11.550 回答
22

$.each 遍历数据集合。由于您传递了一个包含 7 个字符的字符串,因此它将针对每个字符进行迭代。看使用示例:

$.each([52, 97], function(index, value) { 
  alert(index + ': ' + value); 
});
于 2012-11-30T15:53:28.947 回答