問題は、イベントが要素を通過しないことです。イベントを で発生させてい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
)。