为什么$ .each()不遍历每个项目? [英] Why doesn't $.each() iterate through every item?
问题描述
我有以下标记包含10 pre
元素,类缩进
:
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>
I使用以下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
然而,这与 $(。indent)符合预期。每个()
:
$(function(){
$(".indent").each(function(index){
alert(index);
});
});
查看 $。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.
为什么会发生这种情况?
Why is this happening?
推荐答案
$.each(".indent", function(index){
不会迭代 $('。indent')
的元素,但会超过。indent
长度为7个字符的字符串。
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
(这里是你的字符串),哈sa 长度
:
jQuery first checks if the first parameter, obj
(here your string), has a length
:
var ...
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
你的字符串长度
(而不是作为一个函数), isObj
是 false
。
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)};
或使用调用
的一个细微之处> 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)};
)
这篇关于为什么$ .each()不遍历每个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!