[英]For loop doesn't recognize my list items that I add using a submit button to the list, how to fix it?
I have a list with initially 3 items , and a input form from where I can submit new items to the list.I have a for loop to toggle a class for the list items when the item is clicked, it works fine on the 3 items that are initially in the list , but when I try it on and new added item id doesn't recognize it at all even if my list length gets bigger. 我有一个最初包含3个项目的列表,还有一个输入表单,我可以从中提交新项目到列表中。我有一个for循环,可以在单击该项目时切换列表项目的类,在这3个项目上都可以正常工作最初在列表中,但是当我尝试使用它时,即使我的列表长度变大,新添加的项目ID也无法识别。
var li = document.getElementsByTagName("li");
function addDoneClass(i) {
return function() {
li[i].classList.toggle("done");
};
}
for(var i = 0; i< li.length; i++) {
li[i].addEventListener("click", addDoneClass(i));
}
Should toggle the "done" class for every list items that are added 应该为添加的每个列表项切换“完成”类
添加项目后,需要更新包含列表的JS变量:
li = document.getElementsByTagName("li");
When you add a new element there's no reason to query the DOM and loop through all the elements again. 添加新元素时,没有理由查询DOM并再次遍历所有元素。 Just add the click handler in whatever code you used to create the new list element. 只需在用于创建新列表元素的任何代码中添加点击处理程序即可。 If you have a list of li
elements that you are keeping for other reasons, you can add this one to the list here too. 如果您有出于其他原因要保留的li
元素列表,也可以在此处将其添加到列表中。
var li = document.getElementsByTagName("li"); var ul = document.getElementById('theList') function addDoneClass() { this.classList.toggle("done") } function addLI(){ let l = document.createElement('li') // make a new li element l.textContent = "New LI" ul.appendChild(l) l.addEventListener("click", addDoneClass) // add your handler } for(var i = 0; i< li.length; i++) { // deal with initial li elements li[i].addEventListener("click", addDoneClass); }
.done{ color:red }
<ul id="theList"> <li>one</li> <li>two</li> <li>three</li> </ul> <button onclick="addLI()"> add </button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.