javascript - 具有相同 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
但结果是一样的。
解决方案
推荐阅读
- python - 使用 argmax 获得索引的散布更新张量
- node.js - Node js express验证器抛出错误
- java - 如果未将 DateFormat 指定为模式的一部分,则将其解析为当前年/月/日
- hibernate - 公式列中的空值检查
- javascript - 为什么我不能让我的表单关闭,以便我可以访问导航栏?
- javascript - jqxgrid 基于另一列上的值的可编辑属性
- c# - WPF TemplateBinding 不适用于每个属性
- javascript - 折叠在 IE11 上不起作用(Object.keys:参数不是对象)
- kotlin - 为什么在 kotlin 中可以取消“重复”功能
- python - 将多列转换为一行(Pandas/Numpy)