用each()进行jQuery DOM操作;

kth*_*oom 7 javascript each jquery dom this

我正在尝试使用每个()使用jQuery同时对几个元素进行一些简单的DOM操作.我得到的结果我不明白.

这是一个jsFiddle,它显示了我想要发生的事情VS实际发生的事情:

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);
});
Run Code Online (Sandbox Code Playgroud)

为什么我会得到我的结果,我怎样才能获得理想的结果呢?

Kar*_*non 4

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

$('.red', this).clone().appendTo($('.blue', this));
Run Code Online (Sandbox Code Playgroud)

小提琴: http: //jsfiddle.net/4T52A/3/

这是一个最佳解决方案:

$('.grey').each(function () {
    var $this = $(this);
    $this.find('.red').clone().appendTo($this.find('.blue'));
});
Run Code Online (Sandbox Code Playgroud)

  • 你可以使用 `this`,只是不作为上下文(因为appendTo方法不接受上下文。)你可以这样做,例如:`$('.red', this).clone().appendTo( $('.blue', this));` http://jsfiddle.net/4T52A/8/ (已经在这个答案中) (2认同)