【问题标题】:Removing li elements from ul从 ul 中删除 li 元素
【发布时间】:2012-08-01 00:48:48
【问题描述】:

考虑到 li 元素的 id,是否可以使用 JavaScript 从 ul 中动态删除几个 li 元素?

关于实际问题的更新:

我有以下列表。

<ul id="attributes" data-role="listview">
    <li id="attrib01">Attribute1</li>
    <li id="attrib02">Attribute2</li>
    <li id="attrib03">Attribute3</li>
    <li id="attrib04">Attribute4</li>
    <li id="attrib05">Attribute5</li>
</ul>

在 ajax 请求/响应之后,如果某个特定属性是“未定义”,我想将其从列表中删除。

if(typeof data.attrib1 === "undefined")
    $("#attrib01").remove();

我已经确定我收到了正确的 ajax 响应。所以,现在的问题是,当我删除 attrib4 时,attrib[1-3] 也被删除了。知道为什么会发生这种情况吗?

【问题讨论】:

  • 我试过 $("#id-of-the-li-element").remove()。删除列表中的所有 li 元素。
  • 如果你把 li 的实际 id 作为你的 jquery 选择器,它不会删除所有的 lis。请附上您尝试过的代码示例。
  • 那么您使用的是 jQuery 吗?你看过文档吗?无论如何,该代码应该只删除一个元素。您是否在重复使用 ID? UL 上的 ID 是不是 LI 上的?
  • @Ashwin 这实际上就是您使用 jQuery 的方式。 jsfiddle.net/eCbGf 你的错误在别处。
  • 此处信息不足,无法使用。运行一个基本的 jQuery 教程,你就会知道如何去做。

标签: javascript jquery html html-lists


【解决方案1】:

试试

var elem = document.getElementById('id');
elem.parentNode.removeChild(elem);

【讨论】:

    【解决方案2】:

    如果你得到元素然后找到它的父元素然后删除元素。从父级如下:

    element = document.getElementById("element-id");
    element.parentNode.removeChild(element);
    

    需要经过父母,所以这是不可避免的。

    【讨论】:

      【解决方案3】:

      $('#id').remove() 是删除单个元素的正确方法。请注意,元素 ID 在 html 中必须是唯一的,并且该调用必须包装在 DOM 就绪函数中。

      This is a working example 基于您的 html。它遍历所有列表项并删除其 id 不存在于数据对象中的项:

      var data = {
          attrib01: "Number 1",
          attrib02: "Number 2",
          attrib04: "Number 4"
      };
      
      $(document).ready(function() {
          $("ul > li").each(function() {
              alert(this.id in data); //check if value is defined
              if(!(this.id in data)) {
                  $(this).remove();
                  // This also works:
                  //$('#'+this.id).remove();
              }            
          });
      });​
      

      也可以只定位和删除单个元素 (Demo),只需执行以下操作:

      $(document).ready(function() {
          $("#attrib04").remove();
      });​
      

      请注意您的 ID - 它们必须完全匹配。 attrib04 != attrib4

      【讨论】:

        【解决方案4】:

        这将使li 元素不可见:

        document.getElementById("id_here").style.visibility = "hidden";
        

        免责声明:它们仍将在 DOM 中

        要从 DOM 中删除元素,请使用 JQuery 的 .remove() 方法:

        $("#id_here").remove();
        

        http://api.jquery.com/remove/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-07-03
          • 2022-12-05
          • 1970-01-01
          • 2013-04-06
          • 2012-08-12
          • 2013-09-18
          • 2016-07-20
          相关资源
          最近更新 更多