<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>a</li>
<li>a</li>
<li>a</li>
<li>a</li>
</ul>
<!-- 绑定事件 用for里面的i,形成闭包,采用立即执行函数 -->
<script type="text/javascript">
var liCol = document.getElementsByTagName('li');
len = liCol.length
for(var i=0; i < len; i++){
(function(i){
liCol[i].addEventListener('click',function(){
console.log(i);
},false)
}(i))
}
</script>
</body>
</html>
先捕获 后冒泡,在执行时,先绑定的先执行
不能冒泡的事件:
focus blur change submit reset select
取消冒泡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.wrapper{
width: 100px;
height: 100px;
background-color: orange;
}
</style>
<body>
<div class="wrapper">
</div>
<!-- 绑定事件 用for里面的i,形成闭包,采用立即执行函数 -->
<script type="text/javascript">
document.onclick = function() {
console.log('xiandea')
}
var div = document.getElementsByTagName('div')[0];
div.onclick = function(e) {
// 取消冒泡 w3c标准
e.stopPropagation();
this.style.background = 'green';
}
</script>
</body>
</html>
stopPropagation cancelBubble:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.wrapper{
width: 100px;
height: 100px;
background-color: orange;
}
</style>
<body>
<div class="wrapper">
</div>
<script type="text/javascript">
document.onclick = function() {
console.log('xiandea')
}
var div = document.getElementsByTagName('div')[0];
div.onclick = function(e) {
stopBubble(e)
this.style.background = 'green';
}
function stopBubble(event) {
if(event.stopPropagation) {
event.stopPropagation();
}else{
event.cancelBubble = true;
}
}
</script>
</body>
</html>
事件委托
利用事件冒泡,和事件源对象进行处理
优点:性能,不需要循环一个个绑定 ;灵活,新的子元素不需要重新绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.wrapper{
width: 100px;
height: 100px;
background-color: orange;
}
</style>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
<script type="text/javascript">
var ul = document.getElementsByTagName('ul')[0];
ul.onclick = function(e) {
var event = e || window.event;
var target = event.target || event.scrElement;
console.log(target.innerText)
}
</script>
</body>
</html>