Two ways to register events in JavaScript

Two ways to register events in JavaScript

  1. Traditional registration method (with uniqueness, the processing function of the subsequent registration event will override the previous processing function)
var btn=document.querySelectorAll('button');
        btn[0].onclick=function(){
            alert('你好');   //不会弹出
        }
        btn[0].onclick=function(){
            alert('我不好');   //会弹出
}
  1. Method listener registration method addEventListener(), before IE9, use attachEvent(), the same element and the same event can register multiple listeners, and execute
    addEventListener(type,listener[,useCapture]) according to the registered event in turn
    . a. type (event type character String, no need to add on, such as click, mouseover)
    b. listener (event processing function, the listener function will be called when the event occurs)
    c. useCapture (optional parameter, is a boolean type, the default value is false)
btn[1].addEventListener('click',function(){
            alert('你好');  //会弹出
})
btn[1].addEventListener('click',function(){
            alert('我不好');  //会弹出
})

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110309583