我需要有一个事件,它将遍历每个被点击的项目,包括用户自己创建的项目。
我有一个“待办事项”列表,默认包含4个项目。您可以在输入字段中输入“to dos”来添加它们。 P.S - 现在我的脚本仅适用于现有项目
var input = document.getElementById("inpText");
var button = document.getElementById("button");
var ul = document.querySelector("ul");
var list = document.getElementsByTagName("li");
function inputLength() {
return input.value.length;
}
function createNewListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
function newElementCreation() {
if (inputLength() > 0) {
createNewListElement();
}
}
function newElementCreationByEnter(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createNewListElement();
}
}
function ElementToggling () {
this.classList.toggle("done");
}
button.addEventListener("click", newElementCreation);
input.addEventListener("keypress", newElementCreationByEnter);
for (var i=0; i<list.length; i++) {
list[i].addEventListener("click", ElementToggling);
}
.done {
text-decoration: line-through;
}
<html>
<head>
<title>
To do list
</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>My to do list for today</h1>
<input id="inpText" type="text" placeholder="enter the value">
<button id="button">Add</button>
<ul>
<li>To brush my teeth</li>
<li>To cover the bed</li>
<li>To dress up</li>
<li>To cook my breakfast</li>
</ul>
</body>
<script type="text/javascript" src="myscript.js"></script>
</html>
您必须在新创建的li上附加click事件。
更新:添加了一个计数器变量以保持总计数的跟踪。
var input = document.getElementById("inpText");
var button = document.getElementById("button");
var ul = document.querySelector("ul");
var list = document.getElementsByTagName("li");
var totalEl = list.length;
console.log('Total element:', totalEl);
function inputLength() {
return input.value.length;
}
function createNewListElement() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
li.addEventListener("click", ElementToggling); // attach the event here
totalEl++; // Increment the count
console.log('Total element:', totalEl);
}
function newElementCreation() {
if (inputLength() > 0) {
createNewListElement();
}
}
function newElementCreationByEnter(event) {
if (inputLength() > 0 && event.keyCode === 13) {
createNewListElement();
}
}
function ElementToggling () {
this.classList.toggle("done");
}
button.addEventListener("click", newElementCreation);
input.addEventListener("keypress", newElementCreationByEnter);
for (let i=0; i<list.length; i++) {
list[i].addEventListener("click", ElementToggling);
}
.done {
text-decoration: line-through;
}
<h1>My to do list for today</h1>
<input id="inpText" type="text" placeholder="enter the value">
<button id="button">Add</button>
<ul>
<li>To brush my teeth</li>
<li>To cover the bed</li>
<li>To dress up</li>
<li>To cook my breakfast</li>
</ul>