Javascript ng-click 父点击通过孩子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28010244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:06:54  来源:igfitidea点击:

ng-click on parent clicks through children

javascripthtmlcssangularjs

提问by Maeh

I have a <div>element which has another <div>element as its child.

我有一个<div>元素,它有另一个<div>元素作为它的子元素。

I added the ng-clickdirective to the parent, and expected it not to be fired when clicking the child. However, it does.

我将ng-click指令添加到父级,并希望在单击子级时不会触发它。但是,确实如此。

<div class="outer" ng-click="toggle()">
    <div class="inner">You can click through me</div>
</div>

Why is it doing this, and how can I avoid it?

为什么要这样做,我该如何避免?

Here's a JSFiddledemonstrating the issue

这是一个演示该问题的JSFiddle

回答by itd

You have to cancel event propagation, so the click event of the parent element won't get called. Try:

您必须取消事件传播,因此不会调用父元素的 click 事件。尝试:

<div class="outer" ng-click="toggle()">
    <div class="inner" ng-click="$event.stopPropagation()">You can click through me</div>
</div>

When you click the child element, its event gets triggered. But it doesn't stop there. First the click event of the child element is triggered, then the click event of the parent element gets triggered and so on. That's called event propagation, To stop event propagation (triggering of the parents click events), you have to use the above function, stopPropagation.

当您单击子元素时,它的事件被触发。但它并不止于此。先触发子元素的点击事件,再触发父元素的点击事件,以此类推。这称为事件传播,要停止事件传播(触发父级单击事件),您必须使用上述函数,stopPropagation.



Working example

工作示例

I added some CSS padding, so the example is clearer. Without padding the child element takes up the whole inner space and you can not click on the parent without clicking on the child.

我添加了一些 CSS 填充,因此示例更清晰。没有填充子元素占据了整个内部空间,你不能在不点击子元素的情况下点击父元素。

回答by Felipe Rugai

If you want to set different functions for the parent and the child, you can send $event as a parameter for the child function and stopPropagation inside of it. Like this:

如果要为父子函数设置不同的函数,可以将 $event 作为子函数的参数发送,并在其中发送 stopPropagation。像这样:

<div class="outer" ng-click="onParentClick()">
    <div class="inner" ng-click="onChildClick($event)">You can click through me</div>
</div>

and in your controller:

并在您的控制器中:

function onChildClick(event){
    event.stopPropagation();
    //do stuff here...
}
function onParentClick(){
    //do stuff here..
}