【问题标题】:Remove everything except child删除除孩子之外的所有内容
【发布时间】:2013-02-20 09:20:42
【问题描述】:
<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>
<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>
<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>

如何安全地删除.parent 中除.child 之外的所有内容?

我正在使用此代码(其中items.child 的堆栈,each.child

items.each(function(){
    $(this).parent().children().each(function(){
       if ($(this).hasClass('child'))
          // do something
       else
          $(this).remove();
    });

    $(this).unwrap(); // remove parent, keep only .child
});

但它不处理纯文本。

【问题讨论】:

    标签: javascript jquery html parent children


    【解决方案1】:

    你说过

    .parent 内部可以有多个.child,我们只保留第一个。所以如果有三个,第二个和第三个应该被删除。

    还有那个

    items.child 的堆栈,每个都是.child

    好的,那我就是这样做的:

    items.parent('.parent').each(function() {
        var parent = $(this),
            child  = parent.children('.child').first();
        child.detach();
        parent.empty().append(child);
    });
    

    这是做什么的:

    1. .child 元素集移动到.parent 元素集。结果集将只有唯一的父母。

    2. 循环通过父母。

    3. 获取每个父级中的第一个 .child 并将其分离。

    4. 清空.parent

    5. 重新附加.child

    最终结果是每个.parent 将只有一个.child(并且没有其他个孩子,无论.child 与否)。

    【讨论】:

    • 起始选择器始终是$(this),即.child,而不是.parent
    • 不确定如何在$(this)中使用它
    • 如果起始选择器始终是子选择器,则代码可能会运行很多次。有没有办法让父母成为起始选择器?
    • 对不起,我忘了说一切都应该在 each() 内完成。我更新了一个问题。
    • @Per Salbark 没办法,each() 永远是.child
    【解决方案2】:

    这里有一个纯 JS 的解决方案:fiddle

    因此,在您的循环中,您可以使用以下内容:

    this.parentNode.innerHTML = this.outerHTML;
    

    如果您必须保留附加的事件处理程序:

    var _this = this.cloneNode(true),
        parent = this.parentNode;
    parent.innerHTML = '';
    parent.appendChild(_this);
    

    【讨论】:

      【解决方案3】:

      这样的事情就可以了;

      $('.parent').on('click', '.child', function(e) {
          var $this = $(this),
              $parent = $this.parent(),
              $children = $parent.find('.child'); // or: $this.siblings('.child');
      
          $parent
              .empty() // Empty the "parent" element
              .append($children); // Re-append all "child" element to "parent"
          $this.focus(); // Focus the (input) element
      });
      

      【讨论】:

      • 如果有多个.child,则会出现错误。
      【解决方案4】:

      这是使用正则表达式的替代方法:

      $('.parent').each(function() {
          $(this).html($(this).html().match("<input class=.child.>"));
      });
      

      【讨论】:

      • 这会因 all sorts 内容而失败(例如&lt;input class="foo"&gt;My child likes ice cream),并通过标记进行完全不必要的往返,从而丢失任何事件处理程序或此类附件给孩子们。
      • 更正了代码,但是是的,事件处理程序将像这样丢失。
      • 然后是史蒂夫的全部内容,他想从items 开始,其中items.child 元素的集合。 (我回答中大约一半的来回是因为他不想做我最初建议的简单事情,这也像你一样做了$(".parent").each,但没有标记往返。)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多