There are three ways to bind events

  • Bind directly in the tag
<button onclick="handleClick()"<button onclick= <button onclick="Alert (' native function ')"</button>Copy the code
  • Get the DOM event binding in the JS event
<button id="btn" onclick="handleClick()">dom event binding </button> document.getelementById ('btn').onclick=handleClick();
Copy the code
  • The event listens for addEventListener and attachEvent

AddEventListener () function syntax:

elementDOM.addEventListener(eventName,handle,useCapture);
Copy the code
parameter instructions
elementDOM DOM elements
eventName Event name. Note that there is no “on” in the event name, such as click, doubleclick, mouseover, mouseout, etc
handle Event handle functions, that is, functions used to handle events.
useCapture Boolean, whether capture is used or not, usually false. This refers to the concept of JavaScript event flow.

AttachEvent () function syntax:

elementDOM.attachEvent(eventName,handle);
Copy the code
parameter instructions
elementDOM DOM elements
eventName Event name. Note that there is no “on” in the event name, such as click, doubleclick, mouseover, mouseout, etc
handle Event handle functions, that is, functions used to handle events.

Compatibility processing

Compatible with Are not compatible
attachEvent IE7 and IE8 Firefox, Chrome, IE9, IE10, IE11, Safari, Opera
addEventListener Firefox, Chrome, IE, Safari, Opera Compatible with Internet Explorer 7 and Internet Explorer 8

Similarities and differences between attachEvent and addEventListener

Similarities: both are dom object methods that can implement one event binding multiple event handlers. Difference:

1. AttachEvent is a method in IE that does not follow the W3C standard. Other mainstream browsers that follow the W3C standard, such as FF, use addEventListener, so it needs to be handled separately in actual development.

2. The execution sequence varies after multiple binding. AttachEvent is bound first, and addEventListener is bound first.

The first two approaches are often used, so why have a third when there are already two ways to bind events?

The difference is that with “addeventListener” you can bind the same event multiple times and both events will be executed, whereas in DOM structures if you bind two “onclick” events, only the first event will be executed. Only the last event is executed when js is bound by an anonymous function.