[英]How do you .unwrap() an element multiple times?
Is there a way to use Jquery's .unwrap()
multiple times without copying and pasting? 有没有办法多次使用Jquery的.unwrap()
而无需复制和粘贴? It'd be nice if it could accept an argument or something like: .unwrap(4)
but it doesn't. 如果它可以接受一个参数或类似的东西会很好: .unwrap(4)
但它没有。 Is there a more clever solution to achieving the following:? 是否有更聪明的解决方案来实现以下目标:?
$(".foo a").unwrap().unwrap().unwrap().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="foo"> <div> <ul> <li> <div> <a href="#">Link 1</a> </div> </li> </ul> </div> </li> <li class="foo"> <div> <ul> <li> <div> <a href="#">Link 2</a> </div> </li> </ul> </div> </li> <li class="foo"> <div> <ul> <li> <div> <a href="#">Link 3</a> </div> </li> </ul> </div> </li> </ul>
Use parentsUntil
使用parentsUntil
the child of foo ( .foo > *
) foo的孩子( .foo > *
)
(which would be an ancestor of the element). (这将是元素的祖先)。
Use addBack
to include the element itself. 使用addBack
包含元素本身。
$('.foo a').parentsUntil('.foo > *').addBack().unwrap();
n
times, this does it:
如果你想要一个能够解开一个对象n
次的泛型函数,它会这样做:
$.fn.unwrapN = function(n) { while(n--) $(this).unwrap(); return $(this); }
You could always write your own: 你总是可以写自己的:
$.fn.unwrapTimes = function(times){
var unwrapCount = times;
return this.each(function(){
var $this = $(this);
for(var i=0;i<unwrapCount;i++){
$this.unwrap();
}
});
};
Obviously the name should be changed but the logic is sound. 显然,名称应该改变,但逻辑是合理的。
Why overcomplicate it? 为什么过于复杂?
var $wrapper = $('li.foo'),
$keep = $wrapper.find('a'),
$result = $wrapper.empty().append($keep);
console.log($result[0].outerHTML);
For single foo
elememt, try utilizing .prependTo()
, .empty()
对于单foo
elememt,尝试利用.prependTo()
.empty()
$(".foo a").prependTo($(".foo").empty());
$(".foo a").prependTo($(".foo").empty());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <li class="foo"> <div> <ul> <li> <div> <a href="#">Link</a> </div> </li> </ul> </div> </li>
For multiple .foo
classes , try 对于多个.foo
类,请尝试
$(".foo a").each(function() {
$(this).prependTo($(this).parents(".foo").empty());
});
http://jsfiddle.net/pu7Lmxfr/5/ http://jsfiddle.net/pu7Lmxfr/5/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.