Addeventlistener dynamically to newly added classe

2020-05-09 16:50发布

Okay, I have a todo app that i'm creating with JS. I have an addtodo function which adds the items when clicked and also runs a for loop for each of these list elements, which have a classname of 'list', to style them. The thing is, the for loop runs everytime I add the todo list which I think add's multiple event listeners to the already existing items with the same function. I'm trying to toggle a class for priority function when clicking on a paragraph with classname of 'thevalue'. My problem is the event listener runs multiple times and cancels the toggle. The first item runs once, which is correct, and the second item runs, twice, and the third runs three times as follow. I will attach the code below. It would be of great help if you could solve my issue.

var theListPara = document.getElementsByClassName('thevalue');

if (theListPara[0]) {
    for (var i = 0; i < theListPara.length; i++) {
        theListPara[i].addEventListener("click", changePriority);
    }

    function changePriority() {
        var theClassName = this.parentElement.classList.contains('normal');

        if (theClassName) {
            this.parentElement.classList.toggle('high');
        }
    }
}

This whole line of code runs whenever the add todo is clicked.

标签: javascript
1条回答
▲ chillily
2楼-- · 2020-05-09 17:19

Event Delegation is the way forward. Its philosophy is very simple, event listener is attached to static-parent-element then it analyses the bubbled event.target. if match is found then the desired operation can be performed.

document.querySelector('.static-parent-element').addEventListener("click", function(e) {
    if(e.target && e.target.classList.contains('thevalue')) {
        // thevalue item found
        if (this.parentElement.classList.contains('normal')) {
            this.parentElement.classList.toggle('high');
        }
    }
});

Element.matches() API can also used to validate element matches a given selector.

The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

if(e.target.matches('.thevalue')){
}
查看更多
登录 后发表回答