Javascript 使用each()进行jQuery DOM操作;

Javascript 使用each()进行jQuery DOM操作;,javascript,jquery,dom,this,each,Javascript,Jquery,Dom,This,Each,我试图使用jQuery使用each()同时对几个元素执行一些简单的DOM操作。我得到了我不明白的结果 下面是一个JSFIDLE,它显示了我希望发生的事情与实际发生的事情: 以下是JS: // Step One: Append one blue box within each grey box $('.grey').append('<div class="blue"></div>'); // Step Two: Make one copy of the red box

我试图使用jQuery使用each()同时对几个元素执行一些简单的DOM操作。我得到了我不明白的结果

下面是一个JSFIDLE,它显示了我希望发生的事情与实际发生的事情:

以下是JS:

// Step One: Append one blue box within each grey box

$('.grey').append('<div class="blue"></div>');

// Step Two: Make one copy of the red box already there, and place it within the new blue box.

$('.grey').each(function () {
    $('.red', this).clone().appendTo('.blue', this);
});
//第一步:在每个灰色框中附加一个蓝色框
$('.grey')。追加('');
//第二步:复制一份已经存在的红盒子,并将其放在新的蓝盒子中。
$('.grey')。每个(函数(){
$('.red',this.clone().appendTo('.blue',this);
});

为什么我会得到我想要的结果?我如何才能得到想要的结果?

这是因为上下文选择器在
.append()
中不起作用。最快的解决方案(不是最优的)是重新创建一个新的jQuery对象:

$('.red', this).clone().appendTo($('.blue', this));
小提琴:

这里有一个最佳解决方案:

$('.grey').each(function () {
    var $this = $(this);
    $this.find('.red').clone().appendTo($this.find('.blue'));
});
试试这个:

//第一步:在每个灰色框中附加一个蓝色框
$('.grey')。追加('');
//第二步:复制一份已经存在的红盒子,并将其放在新的蓝盒子中。
$('.grey')。每个(函数(){
var blue=$('.blue',this);
$('.red',this.clone().appendTo(蓝色);
});

appendTo不是这样工作的,就我个人而言,我只需要使用
$(this)
对象并从中获取您想要的东西

$('.grey').each(function () {                
    $(this).children('.red').clone().appendTo($(this).children('.blue'));
});

使用工作的

Ok,那么整个问题就是您不能在appendTo中使用“this”?您可以使用
this
,只是不能作为上下文(因为appendTo方法不接受上下文)。您可以这样做,例如:
$('.red',this).clone().appendTo($('.blue',this))(已经在这个答案中)@kthornbloom就像凯文说的,你可以。要使用上下文,您需要创建另一个jQuery对象。就像第一个例子。这就是问题应该怎么问的!清晰、精细、正确的格式。@dfsq完全同意,我们可以确定是有经验的用户发布了此问题!
$('.grey').each(function () {                
    $(this).children('.red').clone().appendTo($(this).children('.blue'));
});