我正在尝试创建一个待办事项列表应用程序,在该应用程序中,单击该按钮时,列表元素会切换到checked
添加删除线样式的类。我在一次定位一个列表元素时遇到了麻烦,而且没有检查整个列表。如何为每个项目动态添加事件侦听器?目前,使用以下代码,已检查添加的项目,我无法弄清原因。
我的HTML如下所示:
<div id="body">
<form id="form" onsubmit="newElement()" target="_self">
<input type="text" id="task" placeholder="What's on the agenda?">
</form>
<ul id="list">
<li class = "checked">test</li >
</ul>
</div>
我的函数通过此函数从文本框中获取数据
function newElement() {
event.preventDefault(); // stop default redirect
/* create a list item and put the inputted text within */
var li = document.createElement("li"); // create a list item
var inputValue = document.getElementById("task").value; // value of text box
var t = document.createTextNode(inputValue); // create a text node of the box value
li.appendChild(t); // put the text node in the li
li.addEventListener('click', checkToggle(li)); // add event listener for a click to toggle
// a strikethrough
/* append the li item to the ul */
appendItem("list", li);
}
然后checkToggle
功能显示如下
/* make items get checked when clicked */
function checkToggle(li) {
li.classList.toggle("checked");
}
但是,在加载页面时,已添加时会自动检查每个元素。
您正在执行功能- checkToggle(li)
你应该像addEventListener('click', checkToggle)
没有括号一样附加功能
function newElement() {
event.preventDefault(); // stop default redirect
/* create a list item and put the inputted text within */
var li = document.createElement("li"); // create a list item
var inputValue = document.getElementById("task").value; // value of text box
var t = document.createTextNode(inputValue); // create a text node of the box value
li.appendChild(t); // put the text node in the li
li.addEventListener('click', checkToggle); // add event listener for a click to toggle
// a strikethrough
/* append the li item to the ul */
document.querySelector("ul").appendChild(li);
}
function checkToggle() {
this.classList.toggle("checked");
}
.checked{color: blue;}
<div id="body">
<form id="form" onsubmit="newElement()" target="_self">
<input type="text" id="task" placeholder="What's on the agenda?">
</form>
<ul id="list">
<li class = "checked">test</li >
</ul>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句