ng点击父级点击子级 [英] ng-click on parent clicks through children

查看:80
本文介绍了ng点击父级点击子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<div>元素,该元素还有另一个<div>元素作为其子元素.

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

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

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

<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?

这是 JSFiddle 演示的问题

推荐答案

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

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

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

单击子元素时,将触发其事件.但这并不止于此.首先触发子元素的click事件,然后触发父元素的click事件,依此类推.这就是事件传播,要停止事件传播(触发父母点击事件),您必须使用上面的功能stopPropagation.

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.

我添加了一些CSS填充,因此示例更加清晰.如果不填充,子元素将占据整个内部空间,并且如果不单击子元素,就无法单击父元素.

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.

这篇关于ng点击父级点击子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆