簡體   English   中英

元素事件偵聽器回調不適用於自定義事件

[英]Element event listener callback not working with custom event

元素事件偵聽器回調不適用於自定義事件,在以下代碼中,將觸發文檔和窗口事件偵聽器,但不會觸發元素(在 IE11、FF33 和 Chrome38 上測試,結果相同。)知道嗎? 我是否誤用了自定義事件?

 var el = document.getElementById('some-elem'); el.addEventListener('custom', function (e) { console.log("Element got event: " + e.type); }, false, true); document.addEventListener('custom', function (e) { console.log("document got event: " + e.type); }, false); window.addEventListener('custom', function (e) { console.log("window got event: " + e.type); }, false); var evt = document.createEvent('CustomEvent'); evt.initCustomEvent('custom', true, false); document.dispatchEvent(evt);
 <div id="some-elem"></div>

問題是事件永遠不會通過元素,您在document上觸發事件。 相反,在元素上觸發它:

 var el = document.getElementById('some-elem'); el.addEventListener('custom', function (e) { console.log("Element got event: " + e.type); }, false, true); document.addEventListener('custom', function (e) { console.log("document got event: " + e.type); }, false); window.addEventListener('custom', function (e) { console.log("window got event: " + e.type); }, false); var evt = document.createEvent('CustomEvent'); evt.initCustomEvent('custom', true, false); el.dispatchEvent(evt); // <=== Change is here
 <div id="some-elem"></div>


回復您的評論:

在我的情況下,調度事件的對象與偵聽對象不同,這是否意味着只能在同一對象(窗口和文檔除外)上偵聽自定義事件?

事件必須穿過元素,就像click必須穿過元素才能被元素上的click處理程序看到一樣。 因此,舉例來說,如果你有一個div與事件處理程序就可以了,有一個img內部div ,你派出的事件img ,在處理程序div會觸發因為事件冒泡到它(因為你使事件可以冒泡):

 var el = document.getElementById('some-elem'); el.addEventListener('custom', function (e) { snippet.log("Element got event: " + e.type); }, false, true); document.addEventListener('custom', function (e) { snippet.log("document got event: " + e.type); }, false); window.addEventListener('custom', function (e) { snippet.log("window got event: " + e.type); }, false); var evt = document.createEvent('CustomEvent'); evt.initCustomEvent('custom', true, false); document.getElementById("some-span").dispatchEvent(evt); // <=== Change is here
 <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script><!-- snippet.js details: http://meta.stackexchange.com/a/242144/134069 --> <div id="some-elem"> <span id="some-span"></span> </div>

來自DOM 事件規范的這張圖可能有助於描繪這些東西:

在此處輸入圖片說明

您調用dispatchEvent的元素是“目標”元素(該圖中的深藍色td )。

暫無
暫無

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

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