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