下面是我遇到的问题的重现。我存储$('.box')
到$box
变量中。在我的实际代码中,我$box
在许多地方都使用它来做事,并且工作正常,除了下面的代码部分,我尝试使用$box
jQuery循环遍历页面上的许多内容each()
。我读过关于jQuery的文档each()
,它看起来像它应该工作。我最好的猜测是,将对象存储到变量中会存储DOM看到的第一个元素,而jQuery无法遍历单个元素,但是有知识的人可以解释为什么这不起作用吗?
HTML:
<div class="button">Button</div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
CSS:
.box {
width: 100px;
height: 100px;
margin-top: 10px;
background: dodgerblue;
}
.button {
user-select: none;
width: 200px;
height: 50px;
background: orange;
}
JS:
var $box = $('.box');
$('.button').on('click', function() {
$($box).each(function(i) { // Why does this work?
//$box.each(function(i) { // But this doesn't?
$(this).append(i);
});
});
这是上面与Codepen相同的代码
编辑:正如答案之一指出的那样,我的示例代码中有一个缺陷,使它看起来似乎不起作用,而实际上却起作用了。我已经更新了代码和Codepen以修复该示例。我的JS中必须有其他东西导致此方法不起作用。
尝试下面的代码。您已经将$('。box')对象分配给$ box,请参见此处的小提琴上的工作代码
var $box = $('.box');
$('.button').on('click', function() {
$box.each(function(i) { // Why does this work?
//$box.each(function() { // But this doesn't?
$(this).append(i);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句