簡體   English   中英

如果不知道何時創建事件偵聽器,如何將事件偵聽器添加到HTML元素?

[英]How do I add event listeners to HTML elements if I do not know when they will be created?

我想將我的代碼與Web頁面中的UI分開,我想知道是否存在可以使用的事件,該事件可以告訴我是否創建了元素,因此可以在事件發生時為其分配一個事件處理程序。創建。

例如,如果我有兩個元素,並且每個元素都有事件處理程序,那么我如何知道何時創建這些元素然后添加它們呢?

到目前為止,我所要做的就是將一個偵聽器添加到“ addElement”事件(如果存在)中。 我不知道是否存在。 如果不是,請檢查該元素是否與功能字典中的任何現有ID匹配。 所以像這樣:

來自單獨腳本文件的代碼:

<script>
    // event handler for BorderContainer1282
    function doSomething1() {

    }

    // event handler for Button925
    function doSomething2() {

    }

    var clickHandlersDictionary = {};
    clickHandlersDictionary["BorderContainer1282"] = doSomething1;
    clickHandlersDictionary["Button925"] = doSomething2;


    function createComplete() {
        document.addEventListener("added", addElementEventHandlers);
    }

    function addElementEventHandlers(event) {
        var element = event.currentTarget;

        if (clickHandlersDictionary[element.id]!=null) {
            element.addEventListener("click", clickHandlersDictionary[element.id]);
        }
    }
</script>

和HTML:

<body onReadyState="creationComplete()">
    <div id="BorderContainer1282">
        <input id="Button925" type="button" value="Button">
    </div >
</body>

我認為我可能想做的是依賴注入,但是我不確定。 我可能最終會嘗試支持狀態,並且在創建HTML元素時需要添加和刪除事件偵聽器。

您可以使用MutationObserver MutationObservers允許您檢測DOM的更改並做出相應的反應。

以以下為例:

 /***** Setting up some of your code *****/ function doSomething1() { console.log('Do something 1'); } function doSomething2() { console.log('Do something 2'); } var dictionary = { BorderContainer1282: doSomething1, Button925: doSomething2 }; /***** Setting up the observer *****/ // select the target node var target = document.getElementById('target'); // create an observer instance var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { Object.keys(dictionary).forEach(function(key) { var query = target.querySelector('#' + key); if (query) { query.addEventListener('click', dictionary[key]); } }); }); }); // pass in the target node, as well as the observer options observer.observe(target, { childList: true }); /***** Just adds to the DOM when you click on the button *****/ function addToDom(button) { button.parentNode.removeChild(button); var parentDiv = document.createElement('div'); parentDiv.textContent = 'Parent'; var childDiv1 = document.createElement('div'); childDiv1.textContent = 'BorderContainer1282 (Click Me)'; childDiv1.id = 'BorderContainer1282'; var childDiv2 = document.createElement('div'); childDiv2.textContent = 'Button925 (Click Me)'; childDiv2.id = 'Button925'; parentDiv.appendChild(childDiv1); parentDiv.appendChild(childDiv2); target.appendChild(parentDiv); } 
 <button onclick="addToDom(this)">Add to DOM</button> <div id="target"></div> 

MutationObserver獲取對目標元素的更改(可以是任何元素,僅包括body )。 在這種特殊情況下,它會在添加的節點中搜索與字典中元素的任何匹配項。 如果找到它們,則將相應的功能添加到Click偵聽器。

您需要使用事件委托。

如果您希望在其中創建新元素的目標div的ID為tgt ,則可以這樣編寫事件偵聽器:

document.getElementById("tgt").addEventListener("click",function(event){
    alert(event.target.id);
});

暫無
暫無

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

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