首页 > 解决方案 > 具有相同 javascript 代码的按钮执行不同的操作 [已解决]

问题描述

var toDoList = document.querySelector('.toDoList');
var acceptInput = document.querySelector('.acceptInput');
var mainButton = document.querySelector('.mainButton');
mainButton.addEventListener('click', function (){
    //Make new Li
    const newLi = document.createElement('li');
    const liContent = document.createTextNode(acceptInput.value + "      ");

    //Make done and x buttons
        const doneButton = document.createElement('button');
        const xButton = document.createElement('button');
        //What do the buttons say?
        doneButton.innerHTML = "Done";
        xButton.innerHTML = "X";
        //Program the button
        doneButton.addEventListener('click', function(){
            newLi.remove();
        })
        xButton.addEventListener('click', function(){
            newLi.remove();
        })
        //Add the buttons to the li
        newLi.appendChild(doneButton);
        newLi.appendChild(xButton);
        //Add the user input to it
        newLi.appendChild(liContent);
        //Add the li to the ul
        toDoList.appendChild(newLi);
        toDoList.appendChild(doneButton)
})
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="tdlist.css">
    <title>ToDo List</title>
</head>
<div>
<body>
    <input class="acceptInput" type="text" placeholder="What do you want to do?">
    <br><br>
    <button class="mainButton">Submit</button>
    <br><br>
    <ul class="toDoList">
        
    </ul>
</body>
</div>
<script src="tdlist.js"></script>
</html>

我正在制作一个待办事项列表,列表中的每个 li 都将包含一个“X”或删除按钮和一个“完成”按钮。我计划将来对它们进行区分,但现在,我只希望它们都删除它们的父列表元素。我为这两个按钮添加了相同的代码。但是,“X”按钮可以正常工作,但“完成”按钮会删除整个 ul 而不是其父 li。这是代码:

    //Make new Li
    const newLi = document.createElement('li');
    const liContent = document.createTextNode(acceptInput.value + "      ");
    //Make done and x buttons
        const doneButton = document.createElement('button');
        const xButton = document.createElement('button');
        //What do the buttons say?
        doneButton.innerHTML = "Done";
        xButton.innerHTML = "X";
        //Program the button
        doneButton.addEventListener('click', function(){
            doneButton.parentNode.remove();
        })
        xButton.addEventListener('click', function(){
            xButton.parentNode.remove();
        })
    //Add the user input to it
    newLi.appendChild(liContent);
    //Add the buttons to the li
    newLi.appendChild(doneButton);
    newLi.appendChild(xButton);
    //Add the li to the ul
    toDoList.appendChild(newLi);
    toDoList.appendChild(doneButton)

我也尝试过.parentElement.parentNode但结果是一样的。

标签: javascript

解决方案


推荐阅读