javascript – 使用each()进行jQuery DOM操作;

我正在尝试使用每个()使用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'));
});

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...