The following are the js native events I have compiled for you. Interested students can take a look.
1. Event flow
Event flow is mainly divided into two types: event bubbling and event capture. Events bubble up, and the target element receives the event first, and then gradually propagates upward to less specific nodes. Event capture is exactly the opposite, the main idea is that less specific nodes receive the event first and then gradually propagate down to the target node.
When a div is clicked, the bubbling event receives the node order div->body->html->document
The capture event receives the node order document->html->body ->div
2. Event handler
a) HTML event handler
Each event supported by an element can be handled using an HTML attribute with the same name as the corresponding event handler. specified.
Disadvantages: 1. Time difference problem, the user may have clicked on the page element before the browser has parsed the click event function - wrap the error through try-catch
2. The scope chain of the event handler is different Browsers may produce different results.
3. HTML code and Javascript code are tightly coupled, which is not conducive to expansion and maintenance.
b) DOM0 level event handler
Assign the function to the element event handler attribute
var btn = document.getElementById(“#dv”);
btn.onclick = function(){} ;
The event handler of the element that you want to delete – btn.onclicn = null;
The event handler added in this way is processed in the event bubbling phase.
c)DOM2 level event handler
Specify event handler addEventListener
Remove event handler removeEventListener
Receive three parameters, namely the event name to be processed, the function of the event handler, Boolean Value (true means calling the handler in the capture phase, false means calling the event handler in the bubbling phase)
Note: addEventListener must be deleted through removeEventListener and the parameters must be consistent, so the anonymous function added through addEventListener cannot be removed.
d)IE事件处理程序
attachEvent
detachEvent
两个方法接收相同的两个参数(”onclick”,”function(){}”);
由于IE8级更早版本只支持事件冒泡,所以通过attachEvent添加的事件处理程序只能被添加到冒泡阶段。
注意:attach中第一个参数是onclick而不是addEventListener中的click
IE事件处理程序attachEvent添加的在全局作用域中运行
var btn = document.getElementById(“#tes”); btn.attachEvent(“onclick”,function(){ alert(this == window); //true })
3、跨浏览器的事件处理程序。
由于不同浏览器之间事件处理程序不同,所以有必要编写可以跨浏览器使用的事件处理程序。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of Detailed analysis of js native event description (code attached, simple and clear). For more information, please follow other related articles on the PHP Chinese website!