【问题标题】:jQuery Remove LI from UL with a hyperlink in the LIjQuery 使用 LI 中的超链接从 UL 中删除 LI
【发布时间】:2009-07-13 14:48:48
【问题描述】:

我有一个无序列表:

<ul id="sortable">
  <li id="1" class="ui-state-default">First <a href='#' title='delete' class="itemDelete">x</a></li>
  <li id="2" class="ui-state-default">Second <a href='#' title='delete' class="itemDelete">x</a></li>
  <li id="3" class="ui-state-default">Third <a href='#' title='delete' class="itemDelete">x</a></li>
</ul>

我想从&lt;ul&gt; 中删除&lt;li&gt;。我已经处理了 itemDelete 类的单击事件,我尝试在其中进行删除,但我认为它不起作用,因为我无法删除 &lt;li&gt;,因为孩子正在调用它?

$('.itemDelete').live("click", function() {
            var id = $(this).parent().get(0).id;


            $("#" + id).remove();

        });

最好的方法是什么?

【问题讨论】:

  • 您的 ID 无效 - ID 不能以数字开头
  • @Jon 你的问题对我很有帮助

标签: javascript jquery jquery-ui


【解决方案1】:

假设您使用的是最新版本的 jQuery:

$('#sortable').on('click', '.itemDelete', function() {
    $(this).closest('li').remove();
});

【讨论】:

    【解决方案2】:

    实际上,到目前为止,id 将是未定义的,因为没有一个 li 有 id。

    为什么不这样做

    $(this).parent().remove()
    

    还有,别忘了返回 false。

    【讨论】:

    • 我确实忘记将它们粘贴到原始帖子中
    【解决方案3】:

    您的&lt;li&gt;s 上没有 ID

    简单点怎么样

    $(this).parent().remove();
    

    【讨论】:

      【解决方案4】:

      最终对我有用的是: 用字符串或下划线为您的 id 属性添加前缀(正如其他人指出的那样)

      由于像 jQuery Mobile 这样的框架要求 id 在所有页面中都是唯一的(不仅仅是在一个页面中,所以我会在页面名称、下划线和数字 id 前加上允许我访问数据库中的记录的前缀。

      不要绑定到类或ul控件,而是使用'on'绑定到父列表的li:

          $('#sortable').on('dblclick', 'li'  function() {
              aval = $(this).attr('id').match(/\d+/g); // only want the numbers...
              id = aval[0];
              name = $(this).text(); // in case you need these for a post...
              li = $(this); // so we can remove it from the list after the 'this' object changes inside the ajax call...
              // make an ajax call to the server
              var jqxhr = $.post( "somepage.php", {name: name, id: id},
                  function(data) {
                  li.remove();
                  $("#sortable").listview("refresh");
          },'json').fail(function() { alert("error"); });
          return false;   // preventDefault doesn't seem to work as well...
      });
      

      【讨论】:

        【解决方案5】:

        它也可能正在寻找带有事件的元素的索引

        $('#sortable').on('click', '.itemDelete', function(e) {
            e.preventDefault();
            $(e.target.parentElement).parent()[0].remove();
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-04-06
          • 2019-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-10
          相关资源
          最近更新 更多