[JavaScript] notes-event-event processing

What is an event? Events are signals fired within the browser

Triggering of events: events that occur in the browser itself

The browser in the client is responsible for listening to the event, and when the event is triggered, it is processed through the event handler

Events combined with dom can improve web page interactivity

Three elements of event handling:

(1) Event source: the element node where the event occurs, document, window

(2) Event type: Which event of the listening event source occurs

(3) Event handler: the block of program code executed when an event occurs

One, the way of event handling

There are three types in total, here I only talk about the recommended event handling method

Event listener:

Node.addEventListener('event', callback function, [capture])

advantage:

(1) An event of an element can bind multiple event handlers.

(2) Support the capture phase of event flow (the third parameter is true) and the bubbling phase (the third parameter is false or omitted)

(3) The way at the beginning of DOM can only be used in this way

example:

<a href="#" id="c">刷新</a>
function getIt(){ ; }
function setIt(){ ; }
let el=document.querySelector('a');
el.addEventListener('click',getIt); 
el.addEventListener('click',setIt);

Second, the event handler

Event handlers have named, anonymous, arrow functions

If the event handler is a named or anonymous function, this represents the element reference to which the event handler is bound,

                       If it is an arrow function, do not use this

Anonymous or arrow functions: suitable for event handlers used only once here.

example:

<a href="#" id="c">刷新</a>
let el=document.querySelector('a');
el.addEventListener('blur',function(){
this.innerHTML='你好';
});

Three, named functions (applicable to situations where event handlers may be used multiple times)

When the function has no parameters, only the function name can be written, otherwise it will be called immediately.

When the function has parameters, the function call can only be written in the body of the anonymous function.

function getIt(){this; }
function setIt(temp){this; }
el.addEventListener('blur',getIt);//blur是在元素失去焦点的时候触发
el.addEventListener('blur',function(){
setIt(5);
});

Fourth, delete the listener

Node.removeEventListener('event', callback function, [capture]);

example:

<a href="#" id="c">刷新</a>
let el=document.querySelector('a');
el.addEventListener('click',setIt);
el.addEventListener('click',getIt);
el.removeEventListener('click',getIt);

 

Guess you like

Origin blog.csdn.net/qq_59294119/article/details/125637750