不能删除列表项

Can't remove a list item?

本文关键字:列表 删除列 删除 不能      更新时间:2023-09-26

我正在尝试删除一个列表项。

我像这样添加一个条目:

$('#btnAdd').click(function(){
        var text = $('#item').val();
        if(text.length){
            $('<li />',{html: text}).appendTo('ul.justList')
        }
    });

然后像这样删除它:

 $('#btnRemove').click(function(){
    $("#justList li:last-child").remove();
});

为什么最后一个列表项没有被删除?有什么建议吗?非常感谢!

我想问题可能出在你的标点符号上。请注意.appendTo('ul.justList')$("#justList li:last-child")中"justList"的标点符号差异。

  • ul.justList说,"寻找具有'justList'的<ul>,"或<ul class="justList">

  • #justList说,"查找任何具有'justList'的ID的元素,"或<any-element id="justList">

类和ID是不同的,所以确保你使用正确的标点符号:.表示类,#表示ID。

根据你的添加语句,我猜你需要一个删除语句,如:

$('#btnRemove').click(function(){
    $("ul.justList li:last-child").remove();
});

如果您的add语句正在工作,那么这应该访问相同的ul

请使用。而不是# while remove

$ (' # btnRemove) .click(函数(){

$(".justList li:last-child").remove();

});