我想用 JavaScript 和 HTML 制作自己的杂货/任务列表。我可以毫无问题地将东西添加到列表中,但我有两个问题:
- 如果我将项目添加到列表中,然后按“清除”按钮擦除列表中的所有内容,它就可以工作。但是,当我在清除后将内容添加回列表时,我的控制台会通知我我的数组仍然是空的,尽管屏幕上显示了新任务。
- 我的第二个问题更大。看,我所有的任务都在我认为的数组中,但实际上是一个 HTML 集合。所以,当我尝试设置一个
onclick
事件时,它就不会运行。我不知道为什么,我尝试使用以下问题:Removing HTMLCollection elements from the DOM 。它没有用。我尝试使用item
HTMLCollection item() 方法。没用。我的最后一次尝试是使用for(let thing of...
,但仍然没有结果。
这是我的代码:
let listGro = document.getElementById("list");
let aButton = document.getElementById("add");
let cButton = document.getElementById("clear");
let tasks = document.getElementsByTagName("li");
aButton.onclick = function addItem() {
let newThing = prompt("What do you want to add?"); // asking what the person wants
if (newThing) { // checking if the user actually added something
let newItemList = document.createElement("li"); //create item list
newItemList.className = "item";
let newItemListText = document.createTextNode(newThing); // create text
newItemList.appendChild(newItemListText); // append text
listGro.appendChild(newItemList); // append new element
console.log(`New task added\nNumber of tasks in the list: ${tasks.length}`);
} else {
alert("You can't add nothing");
}
};
cButton.onclick = function clearList() {
var conf = confirm("Are you sure you want to clear the list?");
if (conf && tasks.length != 0) {
for (let i = 0; i < tasks.length; i++) {
tasks[i].style.display = "none";
}
tasks = [];
}
}
for(let thing of tasks) {
//tasks[i].onclick = function removeOrEditItem() {
/*let demand = prompt("Do you want to edit or remove the item?\nPlease answer with 'edit' or 'remove'\nIf this is a mistake, just enter nothing.");
if (demand === "edit") {
let editItem = prompt("What is your new thing?");
tasks[i].innerHTML = editItem;
} else if (demand === "remove") {
tasks[i].splice(i, 1);
}
console.log("clicked");
};*/
// The thing above was a previous attempt with for(let i; i< items.length... you can work with that or below.
thing.onclick = function removeTask() {
thing.style.display = "none";
console.log("removed");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Website template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
</head>
<body>
<h1>Grocery lists manager</h1>
<h2>Welcome! here you can manage your grocery list!</h2>
<ul id = "list"><span>List:</span></ul>
<button id = "add">Add</button>
<button id = "clear">Clear list</button>
</body>
<script src = "script.js"></script>
</html>