The content of this article is to share with you the two methods of preventing event bubbling in js. Friends in need can refer to it
1. Introduction to bubbling events
When we click on a control, if the parent control including this control also has a click event, execution will continue.
Method 1: event.stopPropagation( );
For example:
<p> <p>段落文本内容 <input type="button" value="点击" /> </p></p>
html code:
// 为所有p元素绑定click事件 $("p").click( function(event){ alert("p-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和p的clic; } );
Method 2: event.target
现在,事件处理程序中的变量event保存着事件对象。而event.target属性保存着发生事件的目标元素。这个属性是DOM API中规定的,但是没有被所有浏览器实现 。jQuery对这个事件对象进行了必要的扩展,从而在任何浏览器中都能够使用这个属性。通过.target,可以确定DOM中首先接收到事件的元素(即实际被单击的元素)。而且,我们知道this引用的是处理事件的DOM元素,所以可以编写下列代码:
$(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'); } }) })
此时的代码确保了被单击的元素是
Related recommendations:
The specific implementation method of js preventing event appending
js prevents bubbling and default events (default behavior) detailed explanation
JS prevents users from submitting sample code multiple times_javascript skills
The above is the detailed content of Two ways to prevent event bubbling in js. For more information, please follow other related articles on the PHP Chinese website!