Delegated event handler without jQuery

不羁的心 提交于 2019-12-02 06:46:20

The basic technique for delegation is: set a selectorable attribute on the inner, then attach event handler to the outer, then check for whether the event came from inner:

document.getElementById('outer').addEventListener('mousedown' function(outer_evt) {
    if (outer_evt.target.id == 'inner') {
        // I mousedowned on inner
    }
});

If you have other events attached to outer (this includes events attached to any ancestor of outer), and don't want them fired when you fire the inner event, use outer_evt.stopImmediatePropagation() and/or outer_evt.stopPropagation() (respectively).

If you want to refer to the element that the event bubbled up to, that's .currentTarget. (that is, above, outer_evt.currentTarget === document.getElementById('outer'))

See also EventTarget.addEventListener()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!