Delegated event handler without jQuery

前端 未结 1 1141
我在风中等你
我在风中等你 2021-01-14 17:42

Made this example: https://jsfiddle.net/d8ak0edq/2/

相关标签:
1条回答
  • 2021-01-14 18:29

    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()

    0 讨论(0)
提交回复
热议问题