Addeventlistener dynamically to newly added classes

后端 未结 1 935
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 04:28

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

相关标签:
1条回答
  • 2021-01-26 05:02

    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')){
    }
    
    0 讨论(0)
提交回复
热议问题