Two ways to use JS event monitoring

First of all, let me talk about what is event monitoring,

Event monitoring is to pass a source object of a certain thing (when a certain event occurs), and then transmit a certain event object to the listener, which encapsulates a certain event information, and performs certain processing after receiving the event object. It is event monitoring. Simply put, the school bell is used as the source object of things, and then school is over

There are mainly two methods for setting event monitoring: onclick (click event) and addEventListener();

Let’s talk about the most basic click time first;

html

<button onclick="but(aa)"></button> //点击事件可以是其他标签主要是使用onclick点击事件绑定.

<script>
function but(a){
console.log(a);//打印的传参
}//这是最简单的点击事件
</script>

For events, in addition to the click event, there are more events:

keyboard events

form event monitor

Then another kind of event propagation:

Syntax: addEventListener (parameter 1, parameter 2,)

It is divided into three stages: the capture stage, the target stage, and the bubbling stage in turn.

Parameter 1: event type, this event type does not add on

Parameter 2: Callback function ; Parameter 3: false means event bubbling, true means event capture

The former event is executed first, and the latter event is executed after. Note that IE does not support this method, and other browsers support it

Unbinding event: removeEventListener(event, callback function);//This callback function must be written separately before it can be unbound normally, otherwise it cannot be unbound

Here is a little more about what event bubbling is:

Event bubbling: When the child triggers an event, the child will bubble up to the parent (will propagate to the parent)

The principle is proposed by Microsoft, IE browser supports event bubbling, and there is no event capture in IE browser

Analogy: After a stone hits the bottom of the water, there will be bubbles rising from the bottom of the lake, and you can find the surface from the point

Guess you like

Origin blog.csdn.net/wangxuanyang_zer/article/details/129626758