簡體   English   中英

如何使同樣使用列表項創建的按鈕起作用? 我希望它刪除數組的當前項。 每個項目都有自己的按鈕

[英]How do i make the button that's also created with the list item work? I want it to delete the current item of the array. Each item has it own button

我試圖創建一個 onclick 事件,但什么也沒發生

    let myWork = []
const submitEl = document.getElementById("submit-el")
const clearEl = document.getElementById("clear-el")
const listEl = document.getElementById("list-el")
const textEl = document.getElementById("text-el")

submitEl.addEventListener("click", function () {
    myWork.push(textEl.value)
    renderItems()

})

clearEl.addEventListener("click", function () {
    myWork.pop()
    renderItems()
})

function renderItems() {
    let listItems = ""
    for (let i = 0; i < myWork.length; i++) {
        listItems += `<li>${myWork[i]} </li> <button>Done</button>`
    }
    listEl.innerHTML = listItems
}

如何使此按鈕自行刪除?

如果我理解您的問題,您希望“完成”按鈕在單擊時刪除自己的行。

作為一個快速的解決方案,您可以編寫:

listItems += `<li>${myWork[i]} </li> <button onclick="deleteWorkByIndex(${i})>Done</button>`

function deleteWorkByIndex(index) {
    myWork.splice(index, 1); // Delete the item n°{index}
    renderItems();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM