简体   繁体   中英

How to make the delete button of a list item work

I am currently working on a contact list program. I want to let people being able to delete the contacts on the list through a trash can button. Each of the contact info has its own button and people can delete which ever they want to remove. My code doesn't show any error through inspect (chrome) but the code is not working.

 var demo = document.getElementById("demo"); function addName() { var fname = document.getElementById("fname").value; var entry = document.createElement("li"); var img = document.createElement("img"); img.src = "img/talkbox.png"; $(img).addClass("talkbox"); var deleteBtn = document.createElement("img"); deleteBtn.src = "img/delete.png"; $(deleteBtn).addClass("deleteBtn"); entry.appendChild(img); entry.appendChild(document.createTextNode(fname)); entry.appendChild(deleteBtn); demo.appendChild(entry); document.getElementById('fname').value = ""; }; const trashCan = document.getElementById("trashcan"); trashCan.addEventListener('click', removeEvent); function removeEvent(e) { const list = document.getElementById("demo"); if (e.target.classList.contains('deleteBtn')) { list.removeChild(e.target.parentElement); list.removeChild(list); }; };
 <div> <ul id="contactlist" class=ppl> <li id="pplli"> <img id="wetalk" class="talkbox" src="img/talkbox.png"> <p class="contactname">Aiden<img id="trashcan" class="deleteBtn" src="img/delete.png"></p> </li> <ol id="demo"> </ol> <br> <a href="#addform" class="pplbtn" id="add"><img id="plus" src="img/plus.png"></a> </ul> </div>

const trashCan = document.getElementById("trashcan");

If you have a list of items and you are using this code for it, this isn't going to work because IDs need to be unique in a document. If you create multiple elements and give them all the same ID, when you try to get the element by its ID, the browser won't know which one you are talking about.

On a separate note, you should use appropriate HTML elements to construct your document or you will cause accessibility issues. An image isn't a button. Consider using the <button> element instead.

I'm actually not sure how you are handling the delete work. But if you are planning to delete an item when clicking on the delete button in it. I mean the delete button is inside the item. Then you can just select the item using document.querySelect and use remove method in js. Here is the link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM