我试图在单击div中的按钮时触发一个函数,而在单击div时触发另一个函数。当我点击button
div
时,也会点击该按钮。单击按钮时div
无法点击
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div style="width:400px;height:400px;background:blue" ng-app="myApp" ng-controller="myCtrl" ng-click="divC()">
<button ng-click="myfun()" style="float:right;top:0">
CLICK
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myfun = function(){
alert("button")
};
$scope.divC = function(){
alert("div")
};
});
</script>
</body>
</html>
答案 0 :(得分:2)
您将需要使用event.stopPropagation()
,这将阻止点击冒泡到其容器。
https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div style="width:400px;height:400px;background:blue" ng-app="myApp" ng-controller="myCtrl" ng-click="divC()">
<button ng-click="myfun($event)" style="float:right;top:0">
CLICK
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myfun = function(event){
event.stopPropagation();
alert("button")
};
$scope.divC = function(){
alert("div")
};
});
</script>
</body>
</html>
&#13;
答案 1 :(得分:0)
您需要停止event propagation.
将按钮功能更改为:
$scope.myfun = function(){
event.stopPropagation();
alert("button")
};
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div style="width:400px;height:400px;background:blue; z-index:-999;" ng-app="myApp" ng-controller="myCtrl" ng-click="divC()">
<button ng-click="myfun()" style="float:right;top:0; z-index:100">
CLICK
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myfun = function(){
event.stopPropagation();
alert("button")
};
$scope.divC = function(){
alert("div")
};
});
</script>
</body>
</html>
&#13;
答案 2 :(得分:0)
您可以使用event
对象(e)并使用它的target
属性来确定由哪个元素调用click
事件。
$("div").on("click", function(e)
{
var target = $(e.target);
if(target.is('button'))
alert('button clicked');
});