search
HomeWeb Front-endJS TutorialJavaScript event parsing

JavaScript event parsing

Feb 11, 2018 am 11:24 AM
javascriptjsevent

Events are actions or things that occur within the system during programming. The system uses it to tell the programmer that if the programmer is willing, the programmer will respond to it in a certain way. This article mainly shares JavaScript event analysis with you, hoping to help everyone.

Add event method

Element attributes

<span style="font-size: 14px;">var btn = document.querySelector('button');<br><br>btn.onclick = function() {<br>  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';<br>  document.body.style.backgroundColor = rndCol;<br>}<br><br>或者<br><br>var btn = document.querySelector('button');<br><br>function bgChange() {<br>  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';<br>  document.body.style.backgroundColor = rndCol;<br>}<br><br>btn.onclick = bgChange<br></span>

Inline events

<span style="font-size: 14px;"><button onclick="bgChange()">Press me</button><br><br>function bgChange() {<br>  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';<br>  document.body.style.backgroundColor = rndCol;<br>}<br><br>或者<br><br><button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button><br></span>

Register event listening

<span style="font-size: 14px;">addEventListener()和removeEventListener();<br><br>btn.addEventListener('click', function() {<br>  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';<br>  document.body.style.backgroundColor = rndCol;<br>});<br><br>或者<br><br>btn.removeEventListener('click', bgChange);<br></span>

Advantages and disadvantages

  • Element attributes

<span style="font-size: 14px;">优:<br>     1. 兼容性好<br>     2. 行为的分离<br>     3.便于操作当事对象,因为function是作为on***的属性出现的,可直接用this引用当事对象<br>缺: <br>     1. 给同一个监听器注册多个处理器,后面的会覆盖前面<br>     btn.onclick=function(){alert('a')};<br>     btn.onclick=function(){alert('b')};<br></span>
  • Inline events

<span style="font-size: 14px;">优:<br>     1. 兼容性好,是最早的事件处理方法<br>     2. 方便快捷<br>缺: <br>     1. 代码杂糅<br>     2. 难以管理和效率低下,一个按钮看起来还好,但是如果有一百个按钮呢?得在文件中加上100个属性<br>     3. 文档很难解析<br></span>
  • Register event listening

<span style="font-size: 14px;">优:<br>     1. 它允许为事件添加多个单独的处理程序。这对于DHTML库或Mozilla扩展尤其有用,即使使用其他库/扩展也需要很好的工作<br>     2. 它可以让你更好地控制阶段,当听者被激活(捕获与冒泡)<br>     3. 它适用于任何DOM元素,而不仅仅是HTML元素<br>     4. 行为的分离 <br>缺:<br>    兼容性(不过网上有很多成熟的hack);<br></span>

Event object

For details, please see event details-https://developer.mozilla.org

  • When an event on the DOM is triggered, an event object event will be generated in the event handler function. This object contains all the events related to the event. information. Includes the element that caused the event, the type of event, and other information related to the specific event.

<span style="font-size: 14px;">var btn = document.getElementById("myBtn");<br>btn.onclick = function(event) {<br>    alert(event.type); //"click"<br>}<br>btn.addEventListener("click", function(event) {<br>    alert(event.type); //"click"<br>}, false);<br></span>

event.currentTarget and event.target

<span style="font-size: 14px;">事件对象event的target属性始终是事件刚刚发生的元素的引用<br></span>
  • For example, you might have a set of 16 squares that disappear when clicked. With e.target you can always select the exact thing you are currently operating on (the square) and perform the action to make it disappear, instead of having to select it in a more difficult way.

<span style="font-size: 14px;">var ps = document.querySelectorAll('p');<br><br>for (var i = 0; i   ps[i].onclick = function(e) {<br>    e.target.style.backgroundColor = bgChange();<br>  }<br>}<br></span>

Prevent default behavior (event.preventDefault())

  • Sometimes, you will encounter some situations where you want the event not to perform its default behavior For example, custom registration form

<span style="font-size: 14px;">var form = document.querySelector('form');<br>var fname = document.getElementById('fname');<br>var lname = document.getElementById('lname');<br>var submit = document.getElementById('submit');<br>var para = document.querySelector('p');<br>form.onsubmit = function(e) {<br>  if (fname.value === '' || lname.value === '') {<br>    e.preventDefault();<br>    para.textContent = 'You need to fill in both names!';<br>  }<br>}<br></span>

Event bubbling and capturing (event.stopPropagation())

<span style="font-size: 14px;">描述事件触发时序问题的术语。<br>事件捕获指的是从document到触发事件的那个节点,即自上而下的去触发事件。<br>事件冒泡是自下而上的去触发事件。<br>绑定事件方法的第三个参数,就是控制事件触发顺序是否为事件捕获。true,事件捕获;false,事件冒泡。默认false,即事件冒泡<br></span>

JavaScript event parsing

Event delegation

<span style="font-size: 14px;">冒泡还允许我们利用事件委托——这个概念依赖于这样一个事实,如果你想要在大量子元素中单击任何一个都可以运行一段代码,您可以将事件监听器设置在其父节点上,并将事件监听器气泡的影响设置为每个子节点,而不是每个子节点单独设置事件监听器<br></span>

For example: the background of the corresponding li turns gray when the mouse is placed on li

<span style="font-size: 14px;"><ul>
<br>    <li>item1</li>
<br>    <li>item2</li>
<br>    <li>item3</li>
<br>    <li>item4</li>
<br>    <li>item5</li>
<br>    <li>item6</li>
<br>
</ul>
<br></span>
  • Use event bubbling to achieve

<span style="font-size: 14px;">$("ul").on("mouseover",function(e){<br>     $(e.target).css("background-color","#ddd").siblings().css("background-color","white");<br>})<br></span>
  • Bind events to all li

<span style="font-size: 14px;">$("li").on("mouseover",function(){<br>      $(this).css("background-color","#ddd").siblings().css("background-color","white");<br>})<br></span>
<span style="font-size: 14px;">代码简洁程度上,两者是相若仿佛的。<br>前者少了一个遍历所有li节点的操作,所以在性能上肯定是更优的<br>如果在绑定事件完成后,页面又动态的加载了一些元素<br>第二种方案,由于绑定事件的时候item7还不存在,所以为了效果,我们还要给它再绑定一次事件.<br></span>

Custom events (DOM event simulation is also called "pseudo-DOM custom events")

  • js native custom events are divided into three stages (creation, initialization, triggering)

##Excerpted from https://developer.mozilla.org...

(1). Create

<span style="font-size: 14px;">var event = document.createEvent(type);<br>type:是一个字符串,表示要创建的事件类型。事件类型可能包括是一个字符串,表示要创建的事件类型。<br>事件类型可能包括"UIEvents", "MouseEvents", "MutationEvents", 或者 "HTMLEvents"<br></span>

(2) Initialize

<span style="font-size: 14px;">event.initEvent('build', true, true);<br>于初始化通过DocumentEvent接口创建的Event的值。支持三个参数:initEvent(eventName, canBubble,preventDefault)<br>分别表示事件名称,是否可以冒泡,是否阻止事件的默认操作<br></span>

(3) . Trigger

<span style="font-size: 14px;">elem.dispatchEvent(event);<br>参数event表示事件对象,是createEvent()方法返回的创建的Event对象<br></span>

Listening method

<span style="font-size: 14px;">elem.addEventListener('build', function (e) {<br>// e.target matches elem<br>}, false);<br></span>
  • jq custom dom event

(1). trigger()

<span style="font-size: 14px;">常用模拟<br>  模拟方法操作<br>   $("#btn").trigger("click");<br>     或者    <br>   $("#btn").click();<br></span>
<span style="font-size: 14px;">自定义事件<br>   $("#btn").on("myClick", function () {<br>       $("#test").append("<p>我的自定义事件。</p>");<br>    });    <br>   $("btn").trigger("myClick");<br></span>
<span style="font-size: 14px;">传递数据<br>  trigger(tpye[,datea]);<br>  第一个参数是要触发的事件类型,<br>  第二个单数是要传递给事件处理函数的附加数据,以数组形式传递。<br>  通常可以通过传递一个参数给回调函数来区别这次事件是代码触发的还是用户触发的<br>   $("#btn").bind("clickCustomize", function (event, message1, message2) { //获取数据<br>        $("#test").append("p" + message1 + message2 + "");<br>   });<br>   $("#btn").trigger("clickCustomize",["我的自定义","事件"]); //传递两个数据<br>   $(“#btn”).trigger(“clickCustomize”,["我的自定义","事件"]); //传递两个数据<br></span>

(2). triggerHandler();(Prevent the default event)

<span style="font-size: 14px;">triggerHandler("lickCustomize");<br></span>
  • DOM custom event advantages and disadvantages:

(1), advantages:

<span style="font-size: 14px;">1、自定义事件完全由我们控制触发时机,这就意味着实现了一种 JavaScript 的解耦。我们可以把多个关联但逻辑复杂的操作利用自定义事件的机制灵活地控制好<br>2、既然绑定也可以解绑,如果不需要了,直接移除绑定事件<br></span>

(2), Disadvantages

<span style="font-size: 14px;">1、兼容性差,要自己hack(jq除外)<br></span>
Related recommendations:

Detailed explanation of JavaScript event handlers

Properties of Javascript events and mouse coordinates

Summary of event streams, handlers and objects for JavaScript event learning

The above is the detailed content of JavaScript event parsing. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor