当用户单击其子元素时,如何防止父单击事件?AngularJS [英] How to prevent parent click event when the user clicks on his child element? AngularJS
本文介绍了当用户单击其子元素时,如何防止父单击事件?AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个< div>
和一个 ng-click
,但是这个< div>
具有一个子元素以及 ng-click
指令.问题在于子元素上的 click事件触发还 父元素的 click事件.
I have a <div>
with a ng-click
but this <div>
have a child element with also a ng-click
directive.
The problem is that the click event on the child element trigger also the click event of the parent element.
当我点击他的孩子时,如何防止父母点击事件?
How can I prevent the parent click event when I click on his child?
这里是一个jsfiddle 来说明我的情况.
预先感谢您的帮助.
编辑
这是我的代码:
<body ng-app ng-controller="TestController">
<div id="parent" ng-click="parentClick()">
<div id="child" ng-click="childClick()"></div>
<p ng-bind="elem"></p>
</div>
<div><p style="text-align:center" ng-bind="childElem"></p></div>
</body>
<script>
function TestController($scope) {
$scope.parentClick = function() {
$scope.elem = 'Parent';
}
var i = 1;
$scope.childClick = function() {
$scope.elem = 'Child';
$scope.childElem = 'Child event triggered x' + i;
i++;
}
}
</script>
推荐答案
您应使用event.stopPropagation()方法.参见: http://jsfiddle.net/qu86oxzc/3/
You should use the event.stopPropagation() method. see: http://jsfiddle.net/qu86oxzc/3/
<div id="child" ng-click="childClick($event)"></div>
$scope.childClick = function($event) {
$event.stopPropagation();
...
}
这篇关于当用户单击其子元素时,如何防止父单击事件?AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文