JavaScript利用事件冒泡这一特性为元素绑定事件,我们将这种操作方式称之为"事件委托"
事件委托简介
事件委托:
指将原本绑定到子元素上的事件,确绑定到父元素
通过父元素监听子元素的冒泡事件,从而达到运行相应事件的效果
例:为每个li标签添加点击事件
当不使用事件委托
则可采用为每个li添加事件的方式增加事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
window.onload = function(){
var the_ul = document.getElementById('list');
var the_li = the_ul.getElementsByTagName('li');
for( var i=0; i < the_li.length; i++ ){
the_li[i].onclick = function(){
console.log(this.innerHTML)
}
}
}
</script>
</body>
</html>
改写为事件委托的写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
window.onload = function(){
var the_ul = document.getElementById('list');
the_ul.onclick = function(e){
console.log(e.target.innerHTML)
}
}
</script>
</body>
</html>
由于采用事件委托的写法,我们只需在ul上绑定事件
当点击li事件时,则采用事件冒泡的方式,触发ul上的事件
此时我们可使用event对象上的target属性找到li标签
例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<ul id="list" style="width: 100px;margin:0;float: left;">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<button style="float:left;" id="addli">添加一个 li</button>
<button style="float:left;" id="delli">删除一个 li</button>
<script>
window.onload = function(){
var the_ul = document.getElementById('list');
var the_li = the_ul.getElementsByTagName('li');
var sum = the_li.length
the_ul.onclick = function(e){
console.log(e.target.innerHTML)
};
document.getElementById('addli').onclick = function (){
var newli = document.createElement("li");
newli.innerHTML = ++sum;
the_ul.appendChild(newli);
};
document.getElementById('delli').onclick = function (){
the_ul.firstElementChild.remove();
};
}
</script>
</body>
</html>
事件委托优点
1.减小内存消耗 使用事件委托可以大量节省内存 减少事件的定义 2.动态绑定事件 在网页中,由于使用事件委托,所以子元素不用考虑事件绑定, 使的事件绑定非常方便