代码之家  ›  专栏  ›  技术社区  ›  Luper Rouch François Lagunas

从jquery集中删除顶级项

  •  1
  • Luper Rouch François Lagunas  · 技术社区  · 14 年前

    我找不到从jquery集中删除顶级项的方法。这是我的尝试:

    <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script>
            $(function() {
                var data = '<div id="node_1">aa</div> <div id="node_2">bb</div> <div id="node_3">cc</div>';
                var nodes = $(data);
                nodes.remove("#node_2");
                $("#container").append(nodes);
            });
        </script>
    </head>
    <body>
        <div id="container"> </div>
    </body>
    </html>
    

    我在集装箱里期待着:

    <div id="container">
        <div id="node_1">aa</div>
        <div id="node_3">cc</div>
    </div>
    

    但是节点2没有被删除。

    如何删除节点2 之前 是否将其插入文档?

    2 回复  |  直到 14 年前
        1
  •  2
  •   AndreKR    14 年前

    显然,现在不能删除不在DOM中的DOM节点。

    您可以使用:

    nodes = nodes.not('#b');
    

    请记住,即使在操作之后(和期间),ID也应该是唯一的。

        2
  •  1
  •   Anthony Corbelli    14 年前

    编辑 -更新后不支持将DIV插入到DOM中,只需在插入前将其移除即可。

    <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script>
            $(function() {
                var data = '<div class="1">aa</div> <div class="2">bb</div> <div class="3">cc</div>';
                $("#container_1").append(data);
                var nodes = jQuery(data).not('.2');   
                // In this example it's '.2',  
                // though you changed your id's in the original to something else
                $("#container_2").append(nodes);
            });
        </script>
    </head>
    <body>
        <div id="container_1"> </div>
        <div id="container_2"> </div>
    </body>
    </html>