jQuery DOM manipulation with each();

I'm trying to do some simple DOM manipulation on several elements at once with jQuery using each(). I'm getting results that I don't understand.

Here is a jsFiddle that shows what I want to happen VS what actually happens:

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

And here is the 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);
});

Why am I getting the results I am, and how can I acheive the desired results?


That is because context selector doesnt work in the .append() . The fastest solution (not optimal) is to recreate a new jQuery object :

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

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

Here an optimal solution :

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

Try this:

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);    
});

The appendTo doesn't work quite that way, personally I'd just use the $(this) object and grab what you want from there.

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

with a working jsFiddle

链接地址: http://www.djcxy.com/p/77876.html

上一篇: 在Bootstrap模式中使用Dropzone.js

下一篇: 使用each()的jQuery DOM操作;