Event Listener - Syntax

event listener

The three elements of an event: event source, event type, and event callback.

Event source: the dom object that needs to be monitored for events
Event type: user behavior that triggers an event, such as: user click onclick, user input oninput, etc.
Event callback: A function that is called when an event is fired.

There are two ways to add event listeners to event sources:

Method 1: Event source. Event type = Event callback
btn.onclick=function(){}
Method 2: Event source.addEventListener (event type, event callback)
//onclick中的on是固定的前缀,比如onmouseover、oninput,真正的事件类型是click
btn.addEventListener('click',function(){})
//如果把一个函数当成参数传给了另外一个函数,这个里面的function(){}是回调函数。

//里面输出了this,那么this指向谁?
btn.addEventListener('click',function(){
  //this指向的是事件源-btn
  //事件回调函数中的this始终指向事件源
  consloe.log(this)
})
In the event callback function, it is fixed to point to the event source, whether it is method 1 or method 2, this points to the event source.

The first method is the old usage before, and the second method is a relatively new syntax. Method 2 is recommended.

The difference between the two methods:
<div class="box"></div>
let box = document.querySelector('.box')

//使用方法一

box.onclick=function () {
  console.log("方法一点击")
}
box.onclick=function () {
  console.log("方法一又被点击")
}
//上述相等于:
let a = 1
a = 2
console.log(a)//a等于几?

//上述添加事件的方法,实际上是在进行赋值的运算,因此重复赋值后,最后一次会将前面的给覆盖掉。

//使用方法二

box.addEventListener('click',function(){
  console.log('方法二点击')
})
box.addEventListener('click',function(){
  console.log('方法二又被点击')
})

//使用方法二添加事件监听时,允许相同事件类型的事件重复被监听。

Guess you like

Origin blog.csdn.net/m0_62181310/article/details/129256991