【问题标题】:jQuery DOM manipulation with each();jQuery DOM 操作 each();
【发布时间】:2014-04-05 00:30:30
【问题描述】:

我正在尝试使用each() 使用jQuery 一次对多个元素进行一些简单的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);
});

为什么我会得到我现在的结果,我怎样才能达到预期的结果?

【问题讨论】:

  • 这就是应该问的问题!清晰,小提琴,正确的格式。
  • @dfsq 完全同意,我们可以确定是有经验的用户发布了这个问题!

标签: javascript jquery dom this each


【解决方案1】:

这是因为上下文选择器在.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'));
});

【讨论】:

  • 好的,所以整个问题就是你不能在 appendTo 中使用“this”?
  • 您可以使用this,但不能用作上下文(因为 appendTo 方法不接受上下文。)例如:$('.red', this).clone().appendTo($('.blue', this)); jsfiddle.net/4T52A/8(即在这个答案中)
  • @kthornbloom 就像凯文说的,你可以。要使用上下文,您需要创建另一个 jQuery 对象。就像第一个例子一样。
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

    appendTo 不是这样工作的,我个人只是使​​用$(this) 对象并从那里获取你想要的东西。

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

    有一个工作的jsFiddle

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 2017-01-02
      • 2016-08-31
      • 2012-09-07
      相关资源
      最近更新 更多