簡體   English   中英

動態將事件監聽器添加到新添加的類

[英]Addeventlistener dynamically to newly added classes

好的,我有一個用JS創建的待辦事項應用程序。 我有一個addtodo函數,該函數可在單擊時添加項目,並為每個列表元素(具有“列表”的類名)運行for循環以設置樣式。 關鍵是,每次我添加待辦事項列表時,for循環都會運行,我認為這是將具有相同功能的多個事件偵聽器添加到已經存在的項目中。 我試圖在單擊類名為“ thevalue”的段落時切換優先級功能的類。 我的問題是事件偵聽器運行多次並取消切換。 第一項運行一次(正確),第二項運行兩次,第三項運行三次,如下所示。 我將在下面附加代碼。 如果您能解決我的問題,那將有很大的幫助。

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');
        }
    }
}

只要單擊添加待辦事項,這行代碼就會運行。

事件委托是前進的道路。 它的原理非常簡單,將事件偵聽器附加到static-parent-element,然后分析冒泡的event.target 如果找到匹配項,則可以執行所需的操作。

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也可用於驗證元素與給定選擇器的匹配。

如果元素將由指定的選擇器字符串選擇,則Element.matches()方法將返回true;否則,該方法將返回true 否則,返回false

if(e.target.matches('.thevalue')){
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM