Write the difference between events and addEventListent() on the element

  1. The onclick add event cannot be bound to more than one event; the later one overwrites the previous one. The addEventListener can add multiple event bindings, executed in sequence.
  2. Onclick can only bubble, addEventListener() can get the capture or bubble.
  3. The addEventListener mode does not support Internet Explorer of earlier versions. AttachEvent supports IE.
  4. After an event is bound in common mode, it cannot be cancelled. After binding addEventListener, you can cancel it with removeEvenListener.
  5. AddEventListener is a method provided in the W3C DOM specification to register event listeners.
AddEventListener usage:

Syntax: element.addEventListener(type, listener, useCapture) — addEventListener — type: – callback: event handler (callback function) – – useCapture: Optional parameter, whether to use event capture to process events. When not passed, the default is false, indicating that event capture is not used (event bubbling is used), or pass True if event capture needs to be displayed.

If you’re not familiar with event capture and bubbling, see: Introduction to JS Event Flow and Preventing Event bubbling

Example:

document.getElementById("item").addEventListener( 'click' , (event) = > {
	console.log(event)
}, false )
Copy the code

The third argument to addEventListener: when true, the browser adopts Capture; when false, the browser adopts bubbing — recommended!

addEventListener

Before IE9, browsers used element.attachevent (type, callback)

attachEvent(type, callback)
Copy the code

Type: event type string, prefixed with “on” callback: event handler (callback function) Note: Because before IE9 only event capture, no event bubble, all attachEvent does not have a third argument.