Home > Article > Web Front-end > Two ways to prevent event bubbling in JavaScript
1. What is JS event bubbling
Trigger a certain type of event on an object (such as click onclick event), if the object defines the event handler, then this event will call this handler. If this event handler is not defined or the event returns true, then this event will propagate to the parent object of this object, from inside to outside, until it is processed (parent All similar events of the object will be activated), or it reaches the top level of the object hierarchy, which is the document object (window in some browsers).
2. Blocking method
Method one: event.stopPropagation( )
<div> <p>段落文本内容 <input type="button" value="点击" /> </p> </div>
// 为所有div元素绑定click事件 $("div").click( function(event){ alert("div-click"); } ); //为所有p元素绑定click事件 $("p").click( function(event){ alert("p-click"); } ); //为所有button元素绑定click事件 $(":button").click( function(event){ alert("button-click"); // 阻止事件冒泡到DOM树上 event.stopPropagation(); // 只执行button的click,如果注释掉该行,将执行button、p和div的click (同类型的事件) } );
Method two: event .target
Now, the variable event in the event handler holds the event object. The event.target attribute stores the target element where the event occurred. This attribute is specified in the DOM API, but is not implemented by all browsers. jQuery makes the necessary extensions to this event object so that this property can be used in any browser. With .target, you can determine the element in the DOM that first received the event (i.e. the element that was actually clicked). Moreover, we know that this refers to the DOM element that handles the event, so we can write the following code:
$(document).ready(function(){ $('#switcher').click(function(event){ $('#switcher .button').toggleClass('hidden'); }) }) $(document).ready(function(){ $('#switcher').click(function(event){ if(event.target==this){//判断是否是当前绑定事件的元素元素触发的该事件 $('#switcher .button').toggleClass('hidden'); } }) })
The code at this time ensures that the clicked element is 1de1e0968f33ca4e1f437b497ef6a3e2, rather than other descendant elements. Clicking the button now no longer collapses the style converter, while clicking the border triggers the collapse action. However, clicking on the label also does nothing because it is also a descendant element. In fact, we can achieve the goal by not putting the checking code here, but by modifying the button's behavior.
The above is the detailed content of Two ways to prevent event bubbling in JavaScript. For more information, please follow other related articles on the PHP Chinese website!