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()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…