AddEventListener differs from on binding events:

  1. AddEventListener can register multiple Listeners for an event, whereas ON can only point to a single object at a time.
window.onload = function () {
    const container = document.querySelector('#container')
    container.onclick = function () {
        console.log('First onClick event')
    }
    container.onclick = function () {
        console.log('Second onClick event')}}// => the second onclick event
Copy the code

Onclick will only execute the second event.

window.onload = function () {
    const container = document.querySelector('#container')
    container.addEventListener('click'.function () {
        console.log('First onClick event')},false)
    container.addEventListener('click'.function () {
        console.log('Second onClick event')},false)}// => first onclick event
// => the second onclick event
Copy the code

The two listeners bound to addEventListener are executed in sequence.

addEventListener("click".function(){},true);
Copy the code

The third argument is true to capture, false to bubble, and false is the default.

<div class="div1">
    <div class="div2">
        <button class="btn">Click on the</button>
    </div>
</div>

const div1 = document.querySelector(".div1")
const div2 = document.querySelector(".div2")
const btn = document.querySelector(".btn")

// False is the default
window.onload=function(){
    btn.addEventListener("click".function () {
        console.log('btn')}); div2.addEventListener("click".function(){
        console.log('div2')
    })
    div1.addEventListener("click".function(){
        console.log('div1')})}// => 执行结果 btn  div2  div1 

// When the third argument is true
window.onload=function(){
    btn.addEventListener("click".function () {
        console.log('btn')},true);
    div2.addEventListener("click".function(){
        console.log('div2')},true)
    div1.addEventListener("click".function(){
        console.log('div1')},true)}// => Result div1 div2 BTN
Copy the code
  1. AddEventListener is valid for any DOM, whereas onClick is limited to HTML.
  2. On event unbinding requires that it be set to None, while addEventListener requires removeEventListener.
/ / on binding
window.onresize = function () { // ... }
/ / on the unbundling
window.onresize = none

/ / addEventListener binding
window.addEventListener('resize'.function () { // ... }, false)
/ / addEventListener unbundling
window.removeEventListener('resize'.function () { // ... }, false)
Copy the code