Event delegation is also called event proxy . The principle is to use the event bubbling mechanism to realize, that is, to bind the event of the child element to the parent element .
For example: there are 100 child elements <a> below the parent element <div>,
Method 1: bind an event to all a, then bind 100 events,
Method 2: Using event delegation, you only need to bind an event to the <div>. When I click on the <a> tag, the event of the <div> tag will be triggered by using the bubbling mechanism. You only need to bind the <div> tag set an event
case:
<div id="lei">
<button>按钮一</button>
<button>按钮二</button>
<button>按钮三</button>
</div>
<script>
var lei = document.getElementById('lei')
lei.addEventListener('click', function (e) {
console.log('我被点击了')
})
</script>
result: