使用jQuery的each()函数进行DOM操作

7
我正在尝试使用jQuery的each()一次性对多个元素进行简单的DOM操作。我得到了一些我不理解的结果。
这里是一个jsFiddle,展示了我想要发生的事情和实际发生的事情:

http://jsfiddle.net/kthornbloom/4T52A/2/

这里是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);
});

我为什么得到当前的结果,如何达到期望的结果?

2
这就是提问的正确方式!清晰、简洁、格式规范。 - dfsq
@dfsq 完全同意,我们可以看出这是一个有经验的用户发布的问题! - Karl-André Gagnon
3个回答

4

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

$('.red', this).clone().appendTo($('.blue', this));

Fiddle :http://jsfiddle.net/4T52A/3/

这里提供了一个最佳解决方案:

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

好的,所以整个问题就是你不能在appendTo中使用"this"吗? - kthornbloom
2
你可以使用 this,但不能作为上下文(因为 appendTo 方法不接受上下文)。例如,你可以这样写:$('.red', this).clone().appendTo($('.blue', this)); http://jsfiddle.net/4T52A/8/ (已经包含在这个答案中了) - Kevin B
@kthornbloom 就像 Kevin 说的那样,你可以这样做。要使用上下文,你需要创建另一个 jQuery 对象。就像第一个例子中一样。 - Karl-André Gagnon

0

试试这个:

http://jsfiddle.net/4T52A/6/

    // 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 () {
    var blue = $('.blue', this);
    $('.red', this).clone().appendTo(blue);    
});

0
appendTo并不完全以这种方式工作,我个人会直接使用$(this)对象,并从其中获取您所需的内容。
$('.grey').each(function () {                
    $(this).children('.red').clone().appendTo($(this).children('.blue'));
});

使用可工作的jsFiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接