Yesterday, an interviewer asked me questions, he asked me directly two div nested, all have the click event, click to pop the child div or the parent div. I don't know why.
After the inquiry after the information, it is very ashamed. It turns out that he was asking about JS capture and bubbling.
I have queried some information:
Event Capture (Parent-"son")
When you use event capture, the parent element is triggered first, the child element is triggered, that is, the div is triggered first, and P is triggered.
Event bubbling (Child--"parent")
When you use event bubbling, the child element is triggered first, the parent element fires, that is, p fires first, and the div fires.
Model
The model is to neutralize the two, and in the model, when any event occurs, the event is captured first from the top level until the event trigger arrives at the event source element. Then, the event bubbles up from the event source until the document is reached.
So can programmers choose what kind of event to trigger? Of course.
The programmer can choose whether to use event capture or event bubbling when binding an event by using the AddEventListener function, which has three parameters, and if the third argument is true, the event is captured, if False, Event bubbling is used.
Ele.addeventlistener (' click ', dosomething2,true)
True= capture
False= Bubble
Traditional bound Event mode
In a browser that supports the DOM, the usual way to bind events is to use event bubbling.
Ele.onclick = DoSomething2
However, IE does not support this addeventlistener, has no three parameters, and does not support event capture. But IE also has a function,attachevent
Ele.attachevent ("onclick", doSomething2);
Attached: event bubbling (The process): the event from which the object occurred (event.srcelement| | Event.target) starts by bubbling up the document up and down, to the documents.
Below the content is from other blogs to take over, can draw lessons from http://blog.csdn.net/xqf309/article/details/8557493
Do a little test. Feel the Bubbling event.
JS event capture and bubbling