【问题标题】:jQuery : remove element except inside elementjQuery:删除除内部元素外的元素
【发布时间】:2011-10-31 09:15:51
【问题描述】:

除了内部元素之外,还有什么方法可以移除元素:

<div class="gallery">
  <a href="images/rep.png" title="rep">
    <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep">
  </a>
</div>

<div class="gallery">
  <img src="http://example.com/uploads/rep.png" class="thumbnail" alt="rep" title="rep">
</div>

我写了这段代码但不起作用:

$(".gallery").contents().filter(".thumbnail").remove();

【问题讨论】:

    标签: jquery dom-manipulation


    【解决方案1】:

    jQuery 有一个unwrap() 方法,它可以移除父节点并将匹配的元素留在原处:

    $(".gallery").contents().filter(".thumbnail").unwrap();
    
    // or (faster)
    $(".gallery .thumbnail").unwrap();
    

    【讨论】:

    • $(".gallery .thumbnail").unwrap();
    【解决方案2】:
    $(".thumbnail").unwrap()
    

    http://api.jquery.com/unwrap/

    【讨论】:

      【解决方案3】:

      可能是一种更简单的方法,但是:

      $('.gallery').each( function() {
      
          var img = $(this).find('img');
          $(this).children("a").remove();
      
          $(this).append(img);
      
      });
      

      【讨论】:

        【解决方案4】:

        试试

        innerhtml = $("div.gallery .thumbnail").get();
        $("div.gallery").html(innerhtml);
        

        【讨论】:

          猜你喜欢
          • 2013-09-23
          • 1970-01-01
          • 2013-07-18
          • 2018-01-17
          • 1970-01-01
          • 1970-01-01
          • 2013-01-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多