Home  >  Article  >  Web Front-end  >  Two ways to prevent event bubbling in js

Two ways to prevent event bubbling in js

不言
不言Original
2018-04-10 14:27:435388browse

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(){
 $(&#39;#switcher&#39;).click(function(event){
  $(&#39;#switcher .button&#39;).toggleClass(&#39;hidden&#39;);
  })
 })
  
$(document).ready(function(){
 $(&#39;#switcher&#39;).click(function(event){
  if(event.target==this){
  $(&#39;#switcher .button&#39;).toggleClass(&#39;hidden&#39;);
  }
  })
 })

此时的代码确保了被单击的元素是6e08cffd95166ffdf6670c2c330eceed ,而不是其他后代元素。现在,单击按钮不会再折叠样式转换器,而单击边框则会触发折叠操作。但是,单击标签同样什么也不会发生,因为它也是一个后代元素。实际上,我们可以不把检查代码放在这里,而是通过修改按钮的行为来达到目标 

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!

Statement:
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