“This is the 20th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Js events are designed to achieve user interaction. For example, when the user clicks the mouse or enters the keyboard, the browser will intercept and inform JS to give feedback and execute corresponding functions to achieve interaction

Today we’ll talk about the various ways native JS can bind events and their differences

  1. Write directly between the lines of the HTML tag
<input type="text" name="user" value=" "style="color:#999" onfocus="if(this.value==' please enter user name '){this.value =" "; This.style. color='#424242'}" onblur="if(this.value == '"){this.value =' please enter username '; this.style.color='#999'}" >Copy the code
  1. ele.onxxx = function(e){}
odiv.onclick = function(e){
  console.log(e);
}
Copy the code

Compatibility is fine, but due to the nature of JS, this assignment is bound to be overridden by subsequent values. So the rule for binding event handlers in this way is that only one handler can be bound to an element and an event. It’s the same thing as the first one between the lines. 3. Ele.addeventlistener (event type, handler,false)

odiv.addEventListener('click',function(e){
    console.log(1);
},false)
odiv.addEventListener('click',function(e){
    console.log(2);
},false)
Copy the code

IE8 and below are not compatible with the addEventListener binding. The same event of the same element can be bound to multiple handlers without being overwritten.

  1. Ele.attachevent (“on”+ event type, handler)
odiv.attachEvent("onclick",function(e){
  console.log(e)
})
odiv.attachEvent("onclick",function(e){
  console.log(e.target)
})
Copy the code

AttachEvent Is similar to addEventListener. An attachEvent event can be bound to multiple handlers of the same element without being overwritten. The difference is that attachEvent can bind functions that can be repeated, that is, even if the same function is bound, it will not be overridden.

Function fn(){console.log(arguments)} odiv.attachevent ("onclick",fn) odiv.attachevent ("onclick",fn) // Print two timesCopy the code

There are a few differences between the “this” and “this” bindings:

  1. Ele.onxxx = fn; This in fn refers to ele itself
  2. Through the ele. AddEventListener (type, fn, false); In fn, this refers to ele itself
  3. Through the ele. AttachEvent (onxxx, fn); This in fn refers to the window

It’s also easier to understand that the special points that are unique to IE point to the Window, and everything else points to the DOM element itself

Encapsulates a compatible method for binding events:

function bindEvent(ele,type,handleFn){ if (ele.addEventListener) { ele.addEventListener(type,handleFn,false); }else if{ ele.attachEvent('on'+type,function(){ handleFn.call(ele) }); }else{ ele['on'+type] = handleFn; }}Copy the code