Javascript 为什么';t$.each()是否遍历每个项目?
我有以下标记,其中包含10个Javascript 为什么';t$.each()是否遍历每个项目?,javascript,iteration,jquery,Javascript,Iteration,Jquery,我有以下标记,其中包含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"&g
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>
我希望看到10个警报,但我只看到7个
但是,对于
$(“.indent”)。each()
:
查看
$。each()
文档,我了解其中的区别:
$.each()函数与$(选择器).each()不同,后者是
用于以独占方式迭代jQuery对象
但我不明白为什么在这个例子中,它没有遍历所有元素
为什么会这样
$.each(".indent", function(index){
不迭代$('.indent')
的元素,而是迭代长度为7个字符的“.indent”
字符串
看
更详细的解释基于: jQuery首先检查第一个参数
obj
(这里是您的字符串)是否有长度
:
var ...
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
您的字符串长度为且不是函数,isObj
是false
在这种情况下,执行以下代码:
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
相当于
for (var i=0; i<".indent".length; i++) {
var letter = ".indent"[i];
f.call(letter, i, letter);
}
对于(var i=0;i您在迭代字符串时,应该将对象或数组传递给$。每个方法:
$(function(){
$.each($(".indent"), function(index){
alert(index);
});
});
$。每个迭代一组数据。由于传递的字符串有7个字符,因此它将对每个字符进行迭代。请参见使用示例:
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
使用console.log
而不是alert
,您将获得更好的调试数据。$。每个(“.indent”)不会在.indent对象上交互。它在.indent上交互string.just side note:最好使用console.log而不是alert。对于测试来说,关闭所有弹出窗口是一件痛苦的事情。@luschn谢谢,早期版本确实使用了console.log()
,但经过数小时的挠头和反复猜测,每一段代码都必须更改,以防:PI在不到一分钟的时间内看到JS加法函数有9次向上投票,而有17次向上投票。each()
…必须向上投票只是为了好玩:)非常感谢。我最近也遇到过类似的问题。+1用于指出value
参数。。。我不知道为什么JQuery决定反转这两个值,通常您希望值
比索引
@Izkata更频繁地使用这个
(好吧,)。这就是为什么index
是最有用的参数,也是第一个参数。
for (var i=0; i<".indent".length; i++) {
var letter = ".indent"[i];
f.call(letter, i, letter);
}
$(function(){
$.each($(".indent"), function(index){
alert(index);
});
});
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});