有两个 onchange
触发器:一个在 INPUT 上,另一个来自包含 INPUT 的 FORM。
document.getElementByTagName('form')[0].addEventListener('change',funcForm); document.getElementByTagName('input')[0].addEventListener('change',funcInput);
funcForm
或funcInput
是否先触发?此行为是否已定义且一致?
如果在第一个触发触发器上发出
e.stopPropagation()
,第二个触发器是否会触发?
最佳答案
应首先触发输入的处理程序,然后事件应在 DOM 层次结构中向上冒泡(如果冒泡)。来自 DOM Events specification :
The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget's parent chain upward
[...]
Any event handler may choose to prevent further event propagation by calling thestopPropagation
method of theEvent
interface. If anyEventListener
calls this method, all additionalEventListeners
on the currentEventTarget
will be triggered but bubbling will cease at that level. Only one call tostopPropagation
is required to prevent further bubbling.
第二段适用于stopPropagation
并表示如果听众在 input
来电 e.stopPropagation()
,那么事件不应达到 <form>
。但是,<input>
上的任何剩余听众将看到更改事件,stopPropagation
只是阻止事件在树中向上冒泡超过 stopPropagation
的级别。被调用。
change
The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.
- Bubbles: Yes
关于javascript - 在 JavaScript 中,如果在 HTML 元素及其祖先上声明事件触发器,哪个先触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6888041/