简体   繁体   English

如何遍历选定的元素并将样式应用于每个元素?

[英]How to iterate through selected elements and apply style to each element?

// I am trying to iterate through the collection of "li" that are returned as result of using the getElementsByTagName method and apply styles to each of them // // 我正在尝试遍历使用 getElementsByTagName 方法返回的“li”集合,并将 styles 应用于它们中的每一个 //

let listItems = document.getElementsByTagName('li')[0];
const addItemInput = document.querySelector('input.addItemInput');
const addItemButton = document.querySelector('button.addItemButton');
const removeItemButton = document.querySelector('button.removeItemButton');

listItems.addEventListener('click', () => {
    let count = listItems.length;
    for(let i = 0; i < count; i++) {
      listItems[i].style.textDecoration = "line-through";
      listItems[i].style.color = "gray";
    }


});

addItemButton.addEventListener('click', () => {
  let todoList = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  li.innerHTML = addItemInput.value;
  todoList.appendChild(li);
  addItemInput.value = "";
});

removeItemButton.addEventListener('click', () => {
  let todoList = document.getElementsByTagName('ul')[0];
  let li = document.querySelector('li:first-child');
  todoList.removeChild(li);
});

listItems isn't an array; listItems不是数组; you're immediately indexing (with [0] ) the collection that getElementsByTagName returns and storing that single element in the (now misleadingly-named) variable.您立即索引(使用[0]getElementsByTagName返回的集合并将该单个元素存储在(现在被误导的名称)变量中。

More fundamentally, it doesn't look like you're looping in the right place, and probably misworded your question.更根本的是,您似乎没有在正确的位置循环,并且可能错误地表达了您的问题。 It looks like you want to be looping over the elements, adding an even listener to each , and have each listener individually re-style the element it's attached to.看起来您想遍历元素,为每个添加一个均匀的侦听器,并让每个侦听器单独重新设置它所附加的元素的样式。

However, that probably still won't actually do what you want, because it'll only hook up the listeners once: new elements won't get one, unless:然而,这可能仍然不会真正做你想做的,因为它只会连接一次监听器:新元素不会得到一个,除非:

  1. You add the listener to each new element as you add it.您在添加每个新元素时将侦听器添加到它。 This would work, but there's a better way.这可行,但还有更好的方法。
  2. You add an event listener to the parent list (that is, the ul element) and catch the click event as it bubbles .您将事件侦听器添加到父列表(即ul元素)并在点击事件冒泡时捕获它 This will require a little more logic inside the event handler, but less elsewhere.这将在事件处理程序中需要更多的逻辑,但在其他地方则更少。

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

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