問題:我想這樣當我點擊一個 li 元素時,會發生一個點擊事件并添加“完成”類。我知道要做到這一點,我需要針對所有 li,并且可以使用 for 回圈,我能夠讓它作業的唯一方法是注釋掉代碼,并創建一個新變數來定位類命名 li,并創建一個回圈,使其以所有 li 專案為目標,并添加“this”thingy,以及單擊事件,將類串列切換為完成。但是一旦我嘗試將它與其余代碼一起添加,它就不起作用了。
let button = document.getElementById("button");
let input = document.getElementById("userinput");
let ul = document.querySelector("ul");
function createListElement() {
let li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = "";
}
function addListAfterClick() {
if (input.value.length > 0) {
createListElement();
}
}
button.addEventListener("click", addListAfterClick);
.done {
text-decoration: line-through;
}
<input type="text" id="userinput">
<button id="button"> </button>
<ul></ul>
uj5u.com熱心網友回復:
您可以向元素添加事件偵聽ul器。如果單擊matches串列項的子元素將新類添加到其classList。
向父元素添加一個偵聽器,該偵聽器在子元素“冒泡”DOM 時捕獲來自其子元素的事件,這稱為事件委托。
const button = document.getElementById('button');
const input = document.getElementById('userinput');
const ul = document.querySelector('ul');
// Add the click listener to the `ul` element
// which calls the `handleClick` handler
ul.addEventListener('click', handleClick);
// Pass in the event to the function, check
// that the clicked element is a list item
// and add a class to it.
function handleClick(e) {
if (e.target.matches('li')) {
e.target.classList.add('done');
}
}
function createListElement() {
let li = document.createElement('li');
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
input.value = '';
}
function addListAfterClick() {
if (input.value.length > 0) {
createListElement();
}
}
button.addEventListener('click', addListAfterClick);
li:hover { cursor: pointer; }
.done { text-decoration: line-through; }
<input type="text" id="userinput">
<button id="button"> </button>
<ul></ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/510240.html
下一篇:您的應用程式中不應有多個路由器
