Home Web Front-end JS Tutorial A brief detailed description of events in JavaScript

A brief detailed description of events in JavaScript

Oct 31, 2017 am 09:55 AM
javascript js

1.Event processingFunction

Events refer to changes in the state of an object that are triggered automatically or manually by the user .

Event handling function: When the event is triggered, automatically executes the function

 The event handling function is essentially an object Special attribute that points to a function.

 Each element object can trigger various events, and each event corresponds to an event handling function.

 When there is no event handling function bound, the event can still be triggered, but since the event binding function is empty at this time, no operation will be performed.

 When the program is executed, the corresponding function or statement is bound to an event processing function of the object. Then once the specified event of the object is triggered, the browser will automatically execute the function. Operations in the object's event handler.

Binding event processing function = assign a value to the on event name (this function)

2. Basic event classification

 1. Mouse event

onclick onbdclick onmousedown onmouseup onmouseover (triggered once when entering the boundary) onmouseout onmusemove

 2. Keyboard events

 onkeydown  onkeyup onkeypress

 3. Status events

onload onunload onchange (select) onfocus (form) onblur (form) onresize onsubmit onreset onerror

3. About event definition

There are three ways to define listening functions for a specific time:

 1. Directly define the event-related attributes of the element in HTML

<p style="margin-bottom: 7px;"><标签 on事件名="fun()/js语句">按钮</标签</p>
Copy after login
<span style="color: #0000ff"><</span><span style="color: #800000">标签 class</span><span style="color: #0000ff">="d1"</span><span style="color: #ff0000"> onclick</span><span style="color: #0000ff">="fun()"</span><span style="color: #0000ff">></span><span style="color: #000000"><span style="color: #ff0000">相当于</span>d1.onclick=function(){
    console.log(this.className);    //d1
    eval("fun()");//[window.]fun
}<br/><strong><span style="color: #ff0000">结论:fun()中this指向window</span></strong></span>
Copy after login
//若要获得当前目标元素对象html:
    onxxx="fun(this)"
js中定义函数时:
    fun(elem);
Copy after login

This method violates " The principle of "separation of content and behavior" should be used as little as possible.

 2. Assign values ​​to the event-related attributes of elements in JavaScript:

elem.on事件名=函数对象;
Copy after login

This method achieves "separation of content and behavior", but elements can only be bound Define a listening function.

 3. Advanced event processing method, one event can be bound to multiple listening functions:

  DOM standard: elem.addEventListener("event name", event object, Whether triggered during the capture phase)

IE8 standard: elem.attachEvent("on event name", event object)

btnObj.attachEvent(&#39;onclick&#39;,function(){});        //IE
btnObj.addEventListener(&#39;click&#39;,function(){});    //DOM
...
doucument.body.attachEvent(&#39;onload&#39;,initData);    //IE
document.body.addEventListener(&#39;load&#39;,initData);    //DOM
function(){
    ...
}
Copy after login

This method can bind multiple listening functions to an element, but You need to pay attention to browser compatibility issues.

Small example: Reverse execution of event processing function

html:

css:

js:

Result:

Original

Click the innermost square result:

##3.Event Cycle

##DOM## After the interpreter creates an event object, It will be propagated among HTML elements

according to the following process:

The first stage: event capture, the event object is propagated downward along the DOM tree (the event model in IE does not have this Phase)

The second phase: the target is triggered and the event listening function is run

The third phase: the event bubbles and the event propagates upward along the DOM tree

1. Event bubbling processing mechanism:

When an object event at the bottom of the DHTML object model occurs, the processing of similar events defined by the object above will be activated in turn

result:

  

IE

  只有两个阶段,没有捕获

4.event对象

  任何事件触发之后都会产生一个event对象

  当事件发生时,自动创建,封装了事件信息(keyCode/screenX/screenY...)

  event对象记录事件发生时的鼠标位置,键盘按键状态和触发对象等信息,事件对象的常用属性:

- secElement(IE) / target(DOM)  :    事件源对象
- eventPhase   :    事件传播的阶段
- clientX/offsetX/pageX/screenX/x    :    事件发生时的X坐标
- clientY/offsetY/pageY/screenY/y    :    事件发生时的Y坐标
- which/keyCode/charCode              :    键盘事件中按下的按键
- button    :    鼠标哪个按键被按下
- cancelBubble    :    是否取消事件冒泡
- returnValue     :    是否阻止事件的默认行为
Copy after login

  1.目标元素对象(从一而终)

    1.HTML绑定事件方式

html:
onclick="fun(event)"  //event必须这样写,不能变

    //实际调用时,event会自动获得当前事件的对象
js:
fun(e){
    //e中获取到的就是当前的事件对象
    }
Copy after login

    2.js绑定方式

//DOM标准:自动创建event对象,默认以第一个参数传入自定义的事件处理函数对象
//IE标准:window全局的event属性,当事件发生时,自动创建event对象,保存在window.event中

var e=window.event||arguments[0];
var src=e.srcElement||e.target;
Copy after login

5.取消冒泡和利用冒泡

  1.取消冒泡

DOM标准:e.stopPropagation()

IE标准:e.cancelBubble=true;

用在当前的事件处理函数的末尾

if(e.stopPropagation)
{
    e.stopPropagation();
}else{
    e.cancelBubble=true;
}
Copy after login

  2.利用冒泡

  优化:若多个子元素中定义了相同的事件处理函数,只需要在共同的父元素上定义一次即可

  原理:事件的捕获和冒泡不会受到程序的干扰,当触发子元素时,会捕获到该元素,然后在父元素触发事件。

6.取消事件

if(e.preventDefault){
    e.preventDefault();    //DOM
}else{
    e.returnValue=false;    //IE
}
Copy after login

  何时取消:eg:表单提交之前,若验证未通过,就取消之后的自动提交。

The above is the detailed content of A brief detailed description of events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles