0

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

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

<!-- first block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

<!-- second block -->
<div class="first">
   My first div
</div>
<div class="second">
   My second div
</div>

...

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

<!-- first block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

<!-- second block -->
<div class="container">
   <div class="first">
      My first div
   </div>    
   <div class="second">
      My second div
   </div>
</div>

...
4

1 回答 1

0

You can do something like this :

$('#btnTest').on('click', function() {
    $("body").append('<div class="container"></div>');
    $("body").append('<div class="container"></div>');

    $(".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();
});

First you add to the DOM the number of div you want with class container. Then for each div .first and .second you have to take the first in the dom $(".first").eq(0) clone it, then append it to the first ".container". You have to use .end() before remove to make sure to remove the original div and not the cloned one.

You do this for each div and you change the ".container" by changing the number in $(".container").eq(0).

This code works fine for your example, but if you have more ".container" you should make a loop of it.

于 2012-12-14T13:27:07.280 回答