JavaScript event parsing
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.length; i++) {<br/> 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>
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 + "</p>");<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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

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

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Methods for building event-based applications in PHP include using the EventSourceAPI to create an event source and using the EventSource object to listen for events on the client side. Send events using Server Sent Events (SSE) and listen for events on the client side using an XMLHttpRequest object. A practical example is to use EventSource to update inventory counts in real time in an e-commerce website. This is achieved on the server side by randomly changing the inventory and sending updates, and the client listens for inventory updates through EventSource and displays them in real time.

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.
