目录
- 简介
 - 示例:事件委托
 - 写法1:事件委托
 - 写法2:每个子元素都绑定事件
 - 示例:新增元素
 - 写法1:事件委托
 - 写法2:每个子元素都绑定事件
 
简介
说明
本文用示例介绍JavaScript中的事件(Event)的委托(代理)的用法。
事件委托简介
事件委托,也叫事件代理,是JavaScript中绑定事件的一种常用技巧。就是将原本需要绑定在子元素的响应事件委托给父元素或更外层元素,让外层元素担当事件监听的职务。
事件代理的原理是DOM元素的事件冒泡。
事件委托的优点
1.节省内存,减少事件的绑定
原本需要绑定在所有子元素的事件,使用事件委托之后,只需要一个事件绑定即可。
2.可以动态绑定事件,新增的子对象事件可以被已绑定的事件处理
因为新增的子对象产生的事件,最终也会冒泡到父元素,从而能够处理
示例:事件委托
需求:一个列表,点击列表元素时弹出其内容。
写法1:事件委托
只需在外层元素绑定事件即可。
<!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>我是第1个li</li>
    <li>我是第2个li</li>
    <li>我是第3个li</li>
</ul>
 
<script>
    let ul = document.getElementById('id-ul');
    ul.addEventListener("click", function (ev) {
        alert(ev.target.innerText);
    })
</script>
 
</body>
</html>
结果

写法2:每个子元素都绑定事件
每个子元素都绑定事件。
<!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>我是第1个li</li>
    <li>我是第2个li</li>
    <li>我是第3个li</li>
</ul>
 
<script>
    let li = document.querySelectorAll('#id-ul li');
    for (let liElement of li) {
        liElement.addEventListener("click", function (ev) {
            alert(ev.target.innerText);
        });
    }
</script>
 
</body>
</html>
结果

示例:新增元素
需求:每点击“生成按钮”,就生成一个子的列表元素。然后,每点击一次列表元素,会弹出其内容。
写法1:事件委托
<!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>1</li>
    <li>2</li>
</ul>
<button id="btn">click</button>
<script>
    let num = 3;
    let eUl = document.querySelector("#id-ul");
    let eButton = document.querySelector("#btn");
 
    eButton.addEventListener("click", function () {
        let newLi = document.createElement("li");
        eUl.appendChild(newLi);
        newLi.innerText = num++;
    })
    eUl.addEventListener("click",function (event) {
        alert(event.target.innerText);
    })
</script>
 
</body>
</html>
结果

可以看到,原有的元素和新建的元素的事件都会被处理。
写法2:每个子元素都绑定事件
<!doctype html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <title>This is title</title>
</head>
 
<body>
 
<ul id="id-ul">
    <li>1</li>
    <li>2</li>
</ul>
<button id="btn">click</button>
<script>
    let num = 3;
    let eUl = document.querySelector("#id-ul");
    let eButton = document.querySelector("#btn");
    let eLi = document.querySelectorAll("#id-ul li");
 
    eButton.addEventListener("click", function () {
        let newLi = document.createElement("li");
        eUl.appendChild(newLi);
        newLi.innerText = num++;
    })
 
    for (let eLiElement of eLi) {
        eLiElement.addEventListener("click",function (event) {
            alert(event.target.innerText);
        })
    }
 
</script>
 
</body>
</html>
结果

可以看到:原有的元素的点击事件会被处理,但新加入的不会被处理。
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
		
评论(0)