簡體   English   中英

用each()進行jQuery DOM操作;

[英]jQuery DOM manipulation with each();

我正在嘗試使用每個()使用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);
});

為什么我會得到我的結果,我怎樣才能獲得理想的結果呢?

這是因為上下文選擇器在.append()不起作用。 最快的解決方案( 非最佳 )是重新創建一個新的jQuery對象:

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

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

這是最佳解決方案:

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

嘗試這個:

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

appendTo不是那么工作,我個人只是使​​用$(this)對象並從那里抓住你想要的東西。

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

有一個工作的jsFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM