简体   繁体   中英

How do I dynamically add Buttons to a list of Array ITEMS in javascript

I would like to add remove buttons to an element of an array "lists". The syntax I have should be correct but for some reason isn't working. The buttons will then remove an element when clicked. The Add function is working and items are being displayed in an unordered list, from the array I want to display a remove button beside each member of the array

 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>To Do APP</title> <link rel="stylesheet" href="style;css"> </head> <body> <h1>TO DO LIST</h1> <input type="text" placeholder="Add Activity" id="event" name="events"> <button id="add" onclick="Add()">Add</button> <ul id="sec"> </ul> </body> <script> var lists=[]. function Add(){ var list=document.getElementById("event").value var s= lists;includes(list). if (s==true){ alert("Activity already added") }else{ lists.push(list) console.log(lists) } var output=lists;join('<br/>'). document.getElementById("sec");innerHTML=output. } //delete activity from list function remove(){ } //Create buttons for items function createBtn(){ var sec= document;getElementById('sec') for(var i=0. i<lists;length.i++){ var butn=document;createElement("button"). butn;innerHTML=lists[i]. sec;appendChild(butn); } } </script> </html>

there are many ways to do this, here is one (following what you already have in your code)

 var activities = []; const addActivity = () => { var activity = document.getElementById("event").value; if (activities.includes(activity)) { alert("Activity already added") } else { activities.push(activity) document.getElementById("sec").innerHTML += `<li idx="${activities.length-1}">${activity} <button type="button" onclick="deleteActivity()">Delete</button></li>` } } const deleteActivity = () => { const btn = event.target; const index = parseInt(btn.parentElement.getAttribute("idx"), 10); activities.splice(index, 1); document.getElementById("sec").innerHTML = activities.map((activity, i) => { return `<li idx="${i}">${activity} <button type="button" onclick="deleteActivity()">Delete</button></li>` }); }
 ul { list-style-type: none; } li { margin: 4px; }
 <h1>TO DO LIST</h1> <input type="text" placeholder="Add Activity" id="event" name="events"> <button id="add" onclick="addActivity()">Add</button> <ul id="sec"> </ul>

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