Home > Web Front-end > JS Tutorial > body text

JavaScript event proxy and delegate instance analysis_javascript skills

WBOY
Release: 2016-05-16 16:07:31
Original
1141 people have browsed it

In JavaScript, we often encounter situations where we need to monitor multiple li items in a list. Suppose we have a list as follows:

Copy code The code is as follows:


  • item1

  • item2

  • item3

  • item4


If we want to implement the following function: when the mouse clicks on a certain li, alert outputs the content of the li. Our usual writing method is like this:

When there are few list items, directly add onclick events to each li
When there are many list items, call the listener for each list item during onload
The first method is relatively simple and direct, but it does not take into account the separation of html and JavaScript and is not recommended. The code for the second method is as follows:

Copy code The code is as follows:

window.onload=function(){
var ulNode=document.getElementById("list");
var liNodes=ulNode.childNodes||ulNode.children;
for(var i=0;i liNodes[i].addEventListener('click',function(e){
alert(e.target.innerHTML);
},false);
}
}

As can be seen from the above, if you keep deleting or adding li, function() will also have to keep changing operations, which is prone to errors. Therefore, it is recommended to use an event proxy. Before using an event proxy, let’s take a look at it first. Event phase:

Event stage:

When a DOM event is triggered, it does not only trigger once on its origin object, but will go through three different stages. In short: the event initially flows from the root node of the document to the target object (capture phase), then is triggered upward on the target pair (target phase), and then traces back to the root node of the document (bubbling phase) as shown in the figure (Image from W3C):

Event capture phase (Capture Phase)

The first phase of the event is the capture phase. The event starts from the root node of the document and flows to the target node of the event along with the structure of the DOM tree. It passes through DOM nodes at various levels on the way, and triggers capture events on each node until it reaches the target node of time. The main task of the capture phase is the resume propagation path. In the bubbling phase, time will be traced back to the document root node through this path.

Copy code The code is as follows:

element.removeEventListener(<event-name>, , );

We use the above function to set monitoring for the node. You can add a monitoring callback function for the capture phase of the event by setting ; to true. In actual applications, we don't have many use cases for using capture phase monitoring, but by handling events in the capture phase, we can prevent click events from being triggered on a specific element.

Copy code The code is as follows:

var form=document.querySeletor('form');
form.addEventListener('click',function(e){
e.stopPropagation();
},true);

이 사용법에 대해 잘 모르는 경우 버블링 단계에서 이벤트를 모니터링하기 위해 false 또는 정의되지 않음으로 설정하는 것이 가장 좋습니다.

목표 단계

이벤트가 대상 노드에 도달하면 이벤트가 대상 단계에 들어갑니다. 이벤트는 대상 노드에서 트리거된 다음 가장 바깥쪽 문서 노드로 전파될 때까지 뒤로 흐릅니다.

다중 레벨 중첩 노드의 경우 마우스 및 포인터 이벤트가 가장 안쪽 요소에 위치하는 경우가 많습니다. div 요소에 클릭 청취 기능을 설정하고 사용자가 div 요소 내부의 p 요소를 클릭하면 이때 p 요소가 대상 요소가 된다고 가정해 보겠습니다. 이벤트 버블링을 사용하면 이 div 또는 상위 수준 요소의 클릭 이벤트를 수신하고 시간 전파 중에 콜백 기능을 트리거할 수 있습니다.

버블 단계

대상 이벤트에서 이벤트가 트리거된 후에는 이 요소에서 종료되지 않습니다. 가장 바깥쪽 루트 노드에 도달할 때까지 DOM 트리를 따라 레이어별로 버블링됩니다. 즉, 대상 노드의 상위 노드, 상위 노드의 상위 노드... 가장 바깥쪽 노드까지 동일한 이벤트가 한 번 트리거됩니다.

대부분의 이벤트가 버블링되지만 전부는 아닙니다. 자세한 내용은 사양

을 참조하세요.

위에서 우리는 이벤트 프록시를 사용하여 각 리를 모니터링할 수 있다고 생각할 수 있습니다. 코드는 다음과 같습니다.

코드 복사 코드는 다음과 같습니다.

window.onload=function(){
var ulNode=document.getElementById("목록");
ulNode.addEventListener('클릭',function(e){
If(e.target&&e.target.nodeName.toUpperCase()=="LI"){/*대상 이벤트가 li인지 확인*/
경고(e.target.innerHTML);
}
},거짓);
};

위 내용은 이 글의 전체 내용입니다. 모든 분들이 JavaScript 이벤트의 위임 및 프록시에 익숙해지는 데 도움이 되기를 바랍니다.

잠시 시간을 내어 기사를 친구들과 공유하거나 댓글을 남겨주세요. 여러분의 지원에 진심으로 감사드립니다!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!