Prevent the default event, and the event delegate cycle

Event period

  1. Event Capture

    dom object from the beginning of the outermost layer, layer by layer down is not bound recorded the event on each target dom, if there is recorded

    Execution order: until the target element from the outer to the inner OFF

  2. The event target event triggers

    Target element of the event trigger

  3. Event bubbling

    From the start of the target element, bubbling up layer by layer trigger (record-bound stage capture event)

    Execution sequence: from the inside

1, when the same event ancestor and descendant elements are bound descendant elements of an event triggers, events will trigger ancestor element

2, the event ancestor, descendant elements can trigger (descendant elements is not bound to the event)

Event listeners:

el.addEventListener ( 'event name', fn [, true / false]);

Third: whether in the capture phase advance trigger defaults to false

How to stop event bubbling

dom Standard: 
calling the next event object a method can prevent
e.stopPropagation ()
IE under
e.cancelBubble = true; Compatibility wording: IF (e.stopPropagation) { e.stopPropagation () } {the else e.cancelBubble = true; } trinocular e.stopPropagation e.stopPropagation ():? = e.cancelBubble to true; a try..catch () the try { e.stopPropagation (); } the catch () { e.cancelBubble = to true; }














Prevent the default event

e.preventDefault()

Event delegates

Principle: use event bubbling, the event will execute the implementation of sub-elements, added to the parent element, the parent element entrust execution

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
ul{
border:1px solid #000000;
}
li{
height:30px;
background: lightcoral;
margin-top:10px;
width:200px;
}
</style>
</head>
<body>
<ul id="list">
<li>1</li>
</ul>
<script>
var arr=[1,2,3,4,5];
var arr2=["a","b","c",'d','e'];
var list = document.getElementById("list");
var str = "";
for(var i=0;i<arr.length;i++){
str += "<li index="+i+">"+arr[i]+"</li>"
}
console.log(str);
list.innerHTML = str;
//获取 li
list.onclick = function(ev){
var e =ev||event;
var target = e.target||e.srcElement;

if( target.nodeName == 'LI' ){
var index =parseInt(target.getAttribute('index'));
alert(arr2[index]);
}
}
</script>
</body>
</html>

 

How to obtain the target element

target property contains a target element in the DOM standard

IE properties srcElement

Compatible: var target = e.target || e.srcElement;

 

Guess you like

Origin www.cnblogs.com/cxf1214/p/11432389.html