我有一个表格,当单击图标时,我试图删除其中的列表项。
因此,当我单击垃圾桶图标,并且仅单击垃圾桶图标时,我想删除该列表项,并将其他项“向上”移动。
<div class="container">
<div class="list">TO-DO LIST<div class="glyphicon glyphicon-plus"></div></div>
<ul class="toDoList" style="list-style: none;">
<li id="addToDo"><input type='text' id="addToDoText" placeholder="Add New ToDo"></input></li>
<li><span><i class="fa fa-trash"></i></span>Buy Robes</li>
<li><span><i class="fa fa-trash"></i></span>Fight Malfoy</li>
<li><span><i class="fa fa-trash"></i></span>Buy New Wand</li>
<li><span><i class="fa fa-trash"></i></span>Kill Voldemort</li>
<li><span><i class="fa fa-trash"></i></span>Feed Hedwig</li>
<li><span><i class="fa fa-trash"></i></span>Send Owl to Sirius</li>
<li><span><i class="fa fa-trash"></i></span>Do Dishes</li>
<li><span><i class="fa fa-trash"></i></span>Wash Robes</li>
<li><span><i class="fa fa-trash"></i></span>Buy Hagrid's Birthday Gift</li>
</ul>
</div>
和我的 jQuery,其中包括用于为表格替代颜色着色的代码,我希望在删除项目时保留该代码。
$(document).ready(function(){
color_table();
});
function color_table(){
$('.toDoList li:nth-child(odd)').addClass('alternate');
};
$('li .fa-trash').on("click", function(){
var index = $(this).index(); // ...doesn't do anything. b/c no index of the class?
var text = $('li').text(); // gets LI text correctly of current item
console.log(index+" // "+text);
$(this).remove(); // This should remove the LI entry, not just the icon class .fa-trash. If I use $('li').remove(), it removes the entire li list! Not just the current one.
color_table();
})
最佳答案
您应该使用closest()
获取祖先li
的方法。
$(this).closest('li').remove();
关于jquery - 从类中删除一个 li 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47621935/