jQuery使用LI中的超链接从UL中删除LI

时间:2009-07-13 14:48:49

标签: javascript jquery jquery-ui

我有一个无序列表:

<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>

我想从<li>中移除<ul>。我已经处理了itemDelete类的click事件,我尝试删除它,但我认为它不起作用,因为我无法删除<li>,因为孩子正在调用它?

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


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

        });

最好的方法是什么?

4 个答案:

答案 0 :(得分:62)

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

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

closestparent更具动态性(虽然parent也适用于此。)它获取最接近当前元素的li,向上结构。

答案 1 :(得分:8)

实际上,截至目前,id的方式将是未定义的,因为没有一个li有id。

为什么不做呢

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

另外,不要忘记返回false。

答案 2 :(得分:6)

您的<li>

上没有ID

如何简单地

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

答案 3 :(得分:0)

为我工作的结果是什么: 使用字符串或下划线(正如其他人指出的那样)为您的id属性添加前缀

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

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

    $('#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...
});
相关问题