我是学习Javascript的新手。我想删除无序列表中的特定列表项。每个项目都有一个删除按钮,我只是无法弄清楚我的按钮如何知道它是否是我选择的项目而不使用它们的索引。
let enterListBtn = document.getElementById("enter");
let input = document.getElementById("userinput");
let ul = document.querySelector("ul");
let togList = document.getElementsByTagName("li");
let deleteBtn = document.getElementById("delete");
function deleteItem() {
togList.parentNode.removeChild(togList);
}
deleteBtn.addEventListener("click", deleteItem);
HTML
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li>Notebook <button id="delete">Delete</button></li>
<li>Jello <button>Delete</button></li>
<li>Spinach <button>Delete</button></li>
<li>Rice <button>Delete</button></li>
<li>Birthday Cake <button>Delete</button></li>
<li>Candles <button>Delete</button></li>
</ul>
<script type="text/javascript" src="script.js"></script>
</body>
答案 0 :(得分:1)
只需为每个删除按钮添加一个类,在jquery add click事件方法中,然后获取按钮的父项将其删除..检查此代码..
$('.delete').on('click', function(){
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li>Notebook <button class="delete">Delete</button></li>
<li>Jello <button class="delete">Delete</button></li>
<li>Spinach <button class="delete">Delete</button></li>
<li>Rice <button class="delete">Delete</button></li>
<li>Birthday Cake <button class="delete">Delete</button></li>
<li>Candles <button class="delete">Delete</button></li>
</ul>
</body>
答案 1 :(得分:0)
您可以使用事件对象定位元素,然后使用parentNode
删除元素
// adda common class to all the buttons
let deleteBtn = document.getElementsByClassName("btn");
// converting html collection to array, to use array methods
Array.prototype.slice.call(deleteBtn).forEach(function(item) {
// iterate and add the event handler to it
item.addEventListener("click", function(e) {
e.target.parentNode.remove()
});
})
&#13;
<h1>Shopping List</h1>
<p id="first">Get it done today</p>
<input id="userinput" type="text" placeholder="enter items">
<button id="enter">Enter</button>
<ul>
<li>Notebook <button class="btn" id="delete">Delete</button></li>
<li>Jello <button class="btn">Delete</button></li>
<li>Spinach <button class="btn">Delete</button></li>
<li>Rice <button class="btn">Delete</button></li>
<li>Birthday Cake <button class="btn">Delete</button></li>
<li>Candles <button class="btn">Delete</button></li>
</ul>
&#13;