如何在jQuery中包装具有不同类名的多个div块? [英] How to wrap multiple div blocks with different class names in jQuery?

查看:107
本文介绍了如何在jQuery中包装具有不同类名的多个div块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Possible Duplicate:
How to wrap DIV tags with different class names in jQuery?

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

I have the following HTML blocks repeated in the document

<!-- 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包装Divs块以获得以下结果...

How can I wrap the blocks of Divs with jQuery to get the following result...

<!-- 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>

...

推荐答案

您可以执行以下操作:

$('#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();
});

首先,将要使用类容器的div数量添加到DOM. 然后,对于每个div .first和.second,您都必须将dom $(".first").eq(0)中的第一个复制它,然后将其附加到第一个".container".在删除之前必须先使用.end(),以确保删除原始div而不是克隆的div.

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.

您对每个div都执行此操作,并通过更改$(".container").eq(0)中的数字来更改".container".

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

此代码在您的示例中正常工作,但是如果您有更多的".container",则应对其进行循环.

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

这篇关于如何在jQuery中包装具有不同类名的多个div块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆