2017-08-11 66 views
1

我正在使用jQuery开发网页。在此网页中,有一个div标签,其中包含pbutton标签。如何阻止jQuery中父元素的点击事件?

HTML码是这样的:

<div class="container"> 
    <div id="attribute" style="border:solid;border-width:2px;border-color:#ccc"> 
     <p id="cell-content" style="display:inline">Id</p> 
     <button id="remark-view" class="btn btn-primary">Detail</button> 
    </div> 
</div> 

和相应JavaScript码是这样的:

$(document).ready(function(){ 
    $("#attribute").on('click', function(){ 
     console.log("click on the div attribute"); 
    }); 
    $("#attribute").on('dblclick', function(){ 
     console.log("double click on the div attribute"); 
    }); 
    $("#remark-view").on('click', function(){ 
     console.log("click on the button remark-view"); 
    }); 
}); 

作为代码所示,一个外div有AP和按钮子元素,和外部div元素侦听单击和双击事件,而内部按钮元素侦听单击事件。

当我在浏览器中运行代码并单击按钮时,控制台显示调用外部div和内部按钮元素的两个单击函数,这违背了我的目的:只有内部按钮的click功能应该被称为在这种情况下。因此,有没有办法阻止父元素(在这种情况下,外部div元素)的click事件。换句话说,是否有任何方法可以在子元素处理它之后停止将父事件传递给父元素?

预先感谢您!

回答

3

stopPropagation函数将停止冒泡DOM的事件。

$("#remark-view").on('click', function(event){ 
     console.log("click on the button remark-view"); 
     event.stopPropagation() 
    }); 

从jQuery的文档

冒泡DOM树,阻止任何 父处理程序被通知的事件阻止事件。

0

这是我在我的一个网站中用来做类似于您的问题的东西。下面的代码所做的是防止中间的div在按钮点击div时关闭。

//Function for the pop up with the background dimmer 
    $(document).mouseup(function(x) { 
    var container = $("#divContent"), 
     dimmer = $('#bgDimmer'); 
    if (container.is(":visible")) { 
     if (!container.is(x.target) //check if the target of the click isn't the container... 
     && container.has(x.target).length === 0) { 
      container.hide(); 
      dimmer.hide(); 
     } 
    } 
}); 

让我们尝试与您的代码相关。

//Function for the pop up with the background dimmer 
    $(document).mouseup(function(x) { 
    var attribute = $('#attribute'); 
    if (attribute.is(":visible")) { 
     if (!attribute.is(x.target) //check if the target of the click isn't the container... 
     && attribute.has(x.target).length === 0) { 
      console.log("click on the button remark-view"); 
     } 
    } 
}); 
+1

答案适用于我的情况,但我认为当页面中的点击监听器数量增加时,可能会遇到麻烦。传单提出的方法可能会更好? – pageajpeng

+0

我不明白'attribute.has(x.target).length === 0'的意思。你能解释它的功能吗? – pageajpeng

+0

这是为了检查容器是否装满或我的情况下,我不认为这将需要你。同意你的更好的答案,但只是作为一个选项发布。 – Sand

相关问题