我需要专门 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");
}
建议?
最佳答案
下面是我将如何去做...
首先,使用 .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/