简体   繁体   English

你怎么.unwrap()一个元素多次?

[英]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();

Fiddle 1 小提琴1


If you want a generic function that unwraps an object n times, this does it: 如果你想要一个能够解开一个对象n次的泛型函数,它会这样做:

 $.fn.unwrapN = function(n) { while(n--) $(this).unwrap(); return $(this); } 

Fiddle 2 小提琴2

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

fiddle 小提琴

Obviously the name should be changed but the logic is sound. 显然,名称应该改变,但逻辑是合理的。

Can use html() 可以用html()

$('.foo').html($('.foo a'));

That approach isn't scaleable for more than one though but can use html(fn) for multiple instances 虽然这种方法不适用于多个实例,但可以将html(fn)用于多个实例

$('.foo').html(function(){
   return $(this).find('a')
});

Demo 演示

Why overcomplicate it? 为什么过于复杂?

var $wrapper = $('li.foo'),
    $keep = $wrapper.find('a'),
    $result = $wrapper.empty().append($keep);

console.log($result[0].outerHTML);

http://jsfiddle.net/k5mn0gnm/ http://jsfiddle.net/k5mn0gnm/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM