如何在jQuery中包装具有不同类名的多个div块?

可能重复:
如何在jQuery中包装具有不同类名的DIV标签?

我在文档中重复了以下HTML块

 
My first div
My second div
My first div
My second div
...

如何用jQuery包装Div块以获得以下结果…

  
My first div
My second div
My first div
My second div
...

你可以这样做:

 $('#btnTest').on('click', function() { $("body").append('
'); $("body").append('
'); $(".first").eq(0) .clone() .appendTo($(".container").eq(0)) .end() .remove(); $(".second").eq(0) .clone() .appendTo($(".container").eq(0)) .end() .remove(); $(".first").eq(0) .clone() .appendTo($(".container").eq(1)) .end() .remove(); $(".second").eq(0) .clone() .appendTo($(".container").eq(1)) .end() .remove(); });

首先,使用类容器向DOM添加所需的div数。 然后对于每个div .first和.second你必须取dom $(".first").eq(0)中的第一个(“。first” $(".first").eq(0)克隆它,然后将它追加到第一个“.container”。 你必须在删除之前使用.end()以确保删除原始div而不是克隆的div。

你为每个div执行此操作,并通过更改$(".container").eq(0)的数字来更改“.container”.eq $(".container").eq(0)

此代码适用于您的示例,但如果您有更多“.container”,则应该对其进行循环。