The title
Write a generic event listener function
function bindEvent(elem,type,selector,fn) {
if (fn == null) {
fn = selector
selector = null
}
elem.addEventLister(type,event= >{
const target = event.target
if (selector) { // Determine the binding type
// Proxy binding
if(target.matches(selector)){ //match determines whether the current triggered element matches the given CSS selector
fn.call(target,event) //call makes this point to the currently triggered element}}else{
// Plain binding
fn.call(target,event) //call makes this point to the currently triggered element}})}Copy the code
Describes the flow of event bubbling
- The behavior of events that are triggered hierarchically based on the DOM structure
Wireless drop-down list of pictures, how to listen to the click of each picture?
- The event agent
- Get the trigger element with e.target
- Matches is used to determine whether the element fires
- Code reference question 1
knowledge
event
- addEventLister
Code examples:
<button id="btn1">A button</button>
Copy the code
/ / the first
var btn = document.getElementById('btn1')
btn.addEventListener('click'.event= > {
console.log('clicked')})Copy the code
The event bubbling
- The event is triggered step by step based on the DOM structure. You can obtain the original triggered element through the event. Target
- StopPropagation Prevents events from bubbling
- The event bubble order is related to the DOM tree structure
Code example: Click the Activate button to activate, click other buttons to cancel
<body>
<div id="div1">
<p id='p1'>The activation</p>
<p id='p1'>cancel</p>
<p id='p1'>cancel</p>
<p id='p1'>cancel</p>
</div>
<div id='div2'>
<p id='p5'>cancel</p>
<p id='p6'>cancel</p>
</div>
</body>
Copy the code
// A simple generic event binding function
function bindEvent(elem,type, fn) {
elem,addEventListener(type,fn)
}
// Events bubble up
var p1 = document.getElementById('p1')
var body = document.body
bindEvent(p1, 'click'.event= > {
event.stopPropagation() // Prevent bubbling
alert('activate')
})
bindEvent(body,'click'.event= > {
alert('cancel')
const target = event.target // Get the element triggered by the event
})
Copy the code
The event agent
- The response to all events under the tag is realized by binding the upper level tag and combining with bubbling. Simple code, reduce browser memory footprint.
- Do not abuse it. It is generally used in DOM applications where the lower DOM is more complex, such as waterfall streams, and other poorly bound events
<div id="div3">
<a href="#">a1</a><br>
<a href="#">a2</a><br>
<a href="#">a3</a><br>
<a href="#">a4</a><br>
<button>Load more...</button>
</div>
Copy the code
// A simple generic event binding function
function bindEvent(elem,type, fn) {
elem,addEventListener(type,fn)
}
// Event broker
const div3 = document.getElementById('div3')
bindEvent(div3, 'click'.event= > {
event.preventDefault()
alert(this.innerHTML)
if(target.nodeName === 'A'){
alert(target.innerHTML)
}
})
Copy the code