繁体   English   中英

单击时如何将 class 切换到元素?

[英]How can I toggle a class to an element when clicked?

问题:我想这样当我点击一个 li 元素时,会发生一个点击事件,并且 class “完成”被添加到它。 我知道要做到这一点,我需要针对所有 li,并且可以使用 for 循环,我能够让它工作的唯一方法是注释掉代码,并创建一个新变量来定位 class命名 li,并创建一个循环,使其以所有 li 项目为目标,并添加“this”thingy 以及单击事件,将 class 列表切换为完成。 但是,一旦我尝试使用代码的 rest 添加它,它就不起作用了。

 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>

您可以将事件侦听器添加到ul元素。 如果单击的子元素与列表项matches ,则将新的 class 添加到其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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM