
事件委托的核心思想是将事件监听器绑定到父元素(或更高级别的祖先元素)上,而不是直接绑定到子元素上。当子元素触发事件时,由于事件冒泡机制,事件会沿着dom树向上传播,最终到达父元素,从而触发父元素上绑定的事件监听器。在事件监听器内部,可以通过event.target属性来确定实际触发事件的子元素,并执行相应的操作。
示例代码:
以下代码演示了如何使用事件委托来处理动态添加的按钮的点击事件。
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
</head>
<body>
<div id="movie-container"></div>
<script>
const movies = [{
image: 'http://t1.gstatic.com/images?q=tbn:ANd9GcQsJW_I8KPZiq4mXcpRCd8uKBsUMR4Gz691k6gwEiLqVOoTl8pf',
title: 'The Life of Brian',
description: 'this is a great movie'
},
{
image: 'https://m.media-amazon.com/images/M/MV5BOTI4MDdjMmUtOTZhOS00MTYwLWEyZTUtYTdhMTQxNGM1YTUxXkEyXkFqcGdeQXVyMzg1ODEwNQ@@._V1_UX140_CR0,0,140,209_AL_.jpg',
title: 'The Wasp Woman',
description: 'this is a terrible movie'
}
];
const movieContainer = document.getElementById('movie-container');
function showMovieInfo(movies) {
movieContainer.innerHTML = "";
movies.forEach(movie => {
movieContainer.innerHTML +=
`
<table class="table align-middle mb-0 bg-white">
<thead class="bg-light">
<tr>
<th>Movie Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="d-flex align-items-center">
<img src="${movie.image}"
alt="" style="width: 120px; height: 120px" class="rounded-circle" />
<div class="ms-3">
<p class="fw-bold mb-1">${movie.title}</p>
<p class="text-muted mb-0">${movie.description}</p>
</div>
</div>
</td>
<td>
<button type="button" data-action="show-on-map" data-title="${movie.title}" class="btn btn-link btn-sm btn-rounded">
Show on map
</button>
</td>
</tr>
</tbody>
</table>`;
});
}
showMovieInfo(movies);
// 使用事件委托
movieContainer.addEventListener('click', function(event) {
const target = event.target;
// 检查点击的元素是否是 "Show on map" 按钮
if (target.tagName === 'BUTTON' && target.dataset.action === 'show-on-map') {
const movieTitle = target.dataset.title;
alert(`Showing ${movieTitle} on map!`);
// 在这里添加显示地图的逻辑
}
});
</script>
</body>
</html>代码解释:
注意事项:
立即学习“前端免费学习笔记(深入)”;
总结:
事件委托是一种高效且灵活的事件处理方式,尤其适用于处理动态添加的元素。通过将事件监听器绑定到父元素上,可以避免重复绑定事件监听器,减少内存消耗,并提高代码的可维护性。在实际开发中,应根据具体情况选择合适的事件处理方式。
以上就是动态添加HTML元素后访问的正确姿势:事件委托机制详解的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号