存储的选择器不能与 each() 一起正常工作
Stored selector doesn't work correctly with each()
下面是我遇到的问题的再现。我将 $('.box')
存储到 $box
变量中。在我的实际代码中,我在许多地方使用 $box
来做事并且它工作正常,除了下面的代码部分,我试图在许多 $box
上使用循环jQuery 的 each()
页面。我已经阅读了关于 each()
的 jQuery 文档,它 看起来 应该可以工作。我最好的猜测是将对象存储到变量中存储 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 请参阅此处 fiddle
上的工作代码
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);
});
});
下面是我遇到的问题的再现。我将 $('.box')
存储到 $box
变量中。在我的实际代码中,我在许多地方使用 $box
来做事并且它工作正常,除了下面的代码部分,我试图在许多 $box
上使用循环jQuery 的 each()
页面。我已经阅读了关于 each()
的 jQuery 文档,它 看起来 应该可以工作。我最好的猜测是将对象存储到变量中存储 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 请参阅此处 fiddle
上的工作代码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);
});
});