【问题标题】:Loop through a container and remove divs without a certain class循环遍历容器并删除没有特定类的 div
【发布时间】:2016-05-03 02:11:43
【问题描述】:

我知道这有一个简单的解决方案。也许是因为太晚了,但我碰壁了。我有一个容器div #jewelsContainer,里面有一个子 div 列表。我在这样的对象中抓取它:

var existingBoardItems = $('#jewelsContainer').html();

此对象生成#jewelsContainer 容器 div 内所有 div 的列表

即之前

<div class="jewel jewel_5" data-row="1" data-col="0" data-jewel="5" style="left: 0px; top: 40px;"></div>
<div class="jewel jewel_3" data-row="0" data-col="3" data-jewel="3" style="top: 0px; left: 120px;"></div>
<div class="jewel jewel_5" data-row="0" data-col="4" data-jewel="5" style="top: 0px; left: 160px;"></div>
<div class="jewel jewel_4" data-row="0" data-col="5" data-jewel="4" style="top: 0px; left: 200px;"></div>
<div class="aff_score" style="left:0px; top:0px;">+10</div>
...

之后

<div class="jewel jewel_5" data-row="1" data-col="0" data-jewel="5" style="left: 0px; top: 40px;"></div>
<div class="jewel jewel_3" data-row="0" data-col="3" data-jewel="3" style="top: 0px; left: 120px;"></div>
<div class="jewel jewel_5" data-row="0" data-col="4" data-jewel="5" style="top: 0px; left: 160px;"></div>
<div class="jewel jewel_4" data-row="0" data-col="5" data-jewel="4" style="top: 0px; left: 200px;"></div>
...

我需要遍历这个对象中的所有 div 并删除任何没有类 .jewel 的 div 然后为新创建的对象设置一个 localStorage

localStorage.setItem('existingBoardItems',NEWELY CREATED OBJECT);

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    尝试在这个上下文中使用:not()选择器,不需要遍历所有的div。

    $('#jewelsContainer div:not(.jewel)').remove();
    

    DEMO

    【讨论】:

    • 谢谢,我知道这很容易解决。我必须睡一觉。
    • @Jason 很高兴为您提供帮助..!
    【解决方案2】:

    虽然答案已被接受,但我觉得非 jQuery 解决方案也应该存在。 :not 不是 jQuery 选择器,它是一个 CSS 选择器,在 jQuery 和本机 querySelectorquerySelectorAll 中都受支持。

    删除上述元素可能是这样的:

    [].forEach.call(document.querySelectorAll('#container :not(.a)'), function(e,i){
        e.parentNode.removeChild(e);
    })
    

    或者这个:

    var elms = document.querySelectorAll('#container :not(.a)');
    for (var i = 0; i < elms.length; i++) {
        elms[i].parentNode.removeChild(elms[i]);
    }
    

    fiddle

    这里有一个jsperf,它表明在这种情况下,香草的速度是原来的两倍多。编辑:似乎它只在 chrome 上更快。

    【讨论】:

      【解决方案3】:

      试试这个方法

      $('#jewelsContainer').find('div').each(function () {
         if (!$(this).hasClass('jewel')) {
              $(this).remove()
          }
      });
      localStorage.setItem('existingBoardItems',$('#jewelsContainer').html());
      console.log(localStorage.getItem('existingBoardItems'));
      

      DEMO

      【讨论】:

      • 这不会删除这个元素.. &lt;div class="jewel_4" ..."&gt;&lt;/div&gt;.. 请改用.hasClass(jewel)..
      • 为什么你能解释一下 sridhar 代码有什么问题。我认为它有效
      • @SridharR 现在看..jsfiddle.net/7M8xL/1。 OP 想要删除没有 jewel.. 类的元素。但这段代码会认为 jewel_4jewel 相同
      • @RajaprabhuAravindasamy 感谢您的解释:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 2012-03-16
      • 2019-11-10
      • 1970-01-01
      • 2018-01-29
      • 2010-09-23
      相关资源
      最近更新 更多