如何在js中对多个li元素应用样式?

问题描述 投票:0回答:1
var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.querySelector("li");

function inputLength() {
    return input.value.length;
}

function createListElement() {
    
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        input.value = "";
}

function addListAfterClick() {
    if (inputLength() > 0) {
        createListElement();
    }
}

function addListAfterKeydown(event) {
    if (inputLength() > 0 && event.key === "Enter") {
        createListElement();
    }
}

button.addEventListener("click", addListAfterClick);
    
input.addEventListener("keydown", addListAfterKeydown);

li.addEventListener("click", function() {
    li.classList.add("done");
} )
.coolTitle {
  text-align: center;
  font-family: 'Oswald', Helvetica, sans-serif;
  font-size: 40px;
  transform: skewY(-10deg);
  letter-spacing: 4px;
  word-spacing: -8px;
  color: tomato;
  text-shadow: 
    -1px -1px 0 firebrick,
    -2px -2px 0 firebrick,
    -3px -3px 0 firebrick,
    -4px -4px 0 firebrick,
    -5px -5px 0 firebrick,
    -6px -6px 0 firebrick,
    -7px -7px 0 firebrick,
    -8px -8px 0 firebrick,
    -30px 20px 40px dimgrey;
}

.done {
  text-decoration: line-through;
}

当我只使用“querySelector”(没有全部)但仅用于第一项时,它第一次起作用。我可以更改什么来为我单击的所有 li 项目应用样式穿线?

我也尝试在 ul 上使用 querySelector 但没有任何反应。

javascript html-lists
1个回答
0
投票

将事件处理程序附加到

ul
,当单击某个项目时,从
li
获取最接近的
e.target
,如果该或它的父级是
li
项目,则将该类添加到
li
项目:

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");

function inputLength() {
  return input.value.length;
}

function createListElement() {
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}

function addListAfterKeydown(event) {
  if (inputLength() > 0 && event.key === "Enter") {
    createListElement();
  }
}

button.addEventListener("click", addListAfterClick);
input.addEventListener("keydown", addListAfterKeydown);

ul.addEventListener("click", function(e) {
  var el = e.target.closest('li');
  if(el) el.classList.add("done");
})
.done {
  text-decoration: line-through;
}
<input id="userinput">

<button id="enter">Add</button>

<ul></ul>

© www.soinside.com 2019 - 2024. All rights reserved.