简体   繁体   中英

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.

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. 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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