为什么 $.each() 不遍历每个项目?

2022-01-24 00:00:00 iteration jquery javascript

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

I have the following markup containing 10 pre elements with the class 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() 函数来遍历每个元素:

I'm using the following jQuery .each() function to iterate through each element:

​$(function(){    
    $.each(".indent", function(index){
       alert(index); 
    });    
});​

我希望看到 10 个警报,但我只看到 7 个

I would expect to see 10 alerts, however I only see 7

-- 见 Fiddle --

但是,这可以与 $(".indent").each() 一起按预期工作:

However, this works as expected with $(".indent").each():

$(function(){    
    $(".indent").each(function(index){
       alert(index); 
    });    
});​

-- 见 Fiddle --

查看 $.each() 文档,我知道有区别:

Looking at the $.each() documentation, I understand theres a difference:

$.each() 函数与 $(selector).each() 不同,它是用于专门迭代 jQuery 对象.

The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.

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

But I don't understand why in this instance, it doesn't iterate through all elements.

为什么会这样?

推荐答案

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

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

doesn't iterate over the elements of $('.indent') but over the ".indent" string whose length is 7 chars.

参见参考

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

A more detailed explanation based on jQuery source code :

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

jQuery first checks if the first parameter, obj (here your string), has a length :

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

您的字符串具有 length(并且不是函数),isObjfalse.

Your string having a length (and not being a function), isObj is false.

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

In this case, the following code is executed :

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

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

So, given the function f, the following code

$.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)}; 记录字母,或者被提醒 call 使用 var f = function(){console.log(this)};)

(you can log the letters using var f = function(i,v){console.log(v)}; or be reminded one of the subtleties of call using var f = function(){console.log(this)};)

相关文章