Jquery:分离() parent 而不影响 child ......解包()做太多了

标签 jquery html css

我需要专门 detach() 一个父 div,同时让子元素完好无损。

unwrap() 对我来说是完美的,但是它删除了 div,我稍后会想恢复它。是否有用于分离的 unwrap() 方法?

例子: CSS:

body{
   background: green;
}

#parent{
    height: 500px;
    width: 500px;
    background: black;
}

#red{
    height: 250px;
    width: 250px;
    background: red;
    float: left;
    margin-top: 100px;
}

html

<body>
    <div id="parent">
        <div id="yellow">yellow</div>
        <div id="red">red</div>  
    </div>   

</body>

j查询

$( document ).ready(function() {

    $("#yellow").click(function(){
          one();
    });

    $("#red").click(function(){
        two();
    });

});

function one(){

    $("#yellow").unwrap();  
}

function two(){

        $("#parent").appendTo("body");
        $("#yellow").appendTo("#parent");
        $("#red").appendTo("#parent"); 
}

http://jsfiddle.net/UzvCR/1/

建议?

最佳答案

下面是我将如何去做...

首先,使用 .clone() 创建父元素的克隆并使用 .empty() 清空内容.

下次使用.unwrap()取出 parent 。

最后,使用.wrapAll()包装克隆。

演示:http://jsfiddle.net/dirtyd77/UzvCR/2/

$( document ).ready(function() {
   //clone the parent and empty out the content
   var clone = $('#parent').clone().empty();

    $("#yellow").click(function(){
          one();
    });

    $("#red").click(function(){
        two();
    });

    function one(){
        //unwraps #parent
        $("#yellow").unwrap();  
    }

    function two(){
        //use .wrapAll
        //perhaps use a class for each child element -- $('.color')
        //so you don't have to use multiple IDs in the selector -- $('#red, #blue, #yellow')
       $("#yellow, #red").wrapAll(clone);
    }  
});

如果您有任何问题,请告诉我!

关于Jquery:分离() parent 而不影响 child ......解包()做太多了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21595892/

相关文章:

javascript - 对文本区域中的某些正则表达式匹配进行颜色编码?

python - 在 Python 中从复选框中提取表单数据

css - 无法让 div 正确 float ,它被向下推

jquery - 如何删除导航和主要内容之间多余的空白?

javascript - 使用 jquery 从头开始​​自动完成

javascript - 如何抢先加载网页或资源?

javascript - 可以使用 CSS 为嵌套图像设置动画吗?

html - 媒体查询未正确调整

javascript - .log 文件的实时更新

html - 我如何自动将 Selenium HTML 测试转换为 Ruby Test::Unit 测试?