元素事件侦听器回调不使用自定义事件

时间:2014-11-08 14:03:36

标签: javascript custom-event

元素事件监听器回调不使用自定义事件,在下面的代码中,将触发文档和窗口事件监听器,但不会触发元素(在IE11,FF33和Chrome38上测试,结果是相同的。)任何的想法?我是否误用了自定义事件?



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.dispatchEvent(evt);

<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"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

问题是事件永远不会通过元素,你在document上触发事件。相反,在元素上触发它:

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);
el.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"></div>


重新评论:

  

调度事件的对象与我的侦听对象不同,这是否意味着只能在同一个对象(窗口和文档除外)上侦听自定义事件?

事件必须遍历元素,就像click必须遍历元素一样,元素上的click处理程序才能看到它。例如,如果你有div的事件处理程序,并且img内有div img,你就调度了事件divvar 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>
dispatchEvent

来自the DOM events spec的图表可能有助于描绘这些内容:

enter image description here

您调用td的元素是“目标”元素(该图中的深蓝色{{1}})。