如何使按钮可点击但其父div?

时间:2016-11-22 21:55:47

标签: javascript jquery html angularjs

我试图在单击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>

3 个答案:

答案 0 :(得分:2)

您将需要使用event.stopPropagation(),这将阻止点击冒泡到其容器。

https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation

&#13;
&#13;
<!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;
&#13;
&#13;

答案 1 :(得分:0)

您需要停止event propagation.

将按钮功能更改为:

$scope.myfun = function(){
  event.stopPropagation();
  alert("button")
};

&#13;
&#13;
<!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;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用event对象(e)并使用它的target属性来确定由哪个元素调用click事件。

$("div").on("click", function(e)
{
  var target = $(e.target);
  if(target.is('button'))
     alert('button clicked');
});

示例:https://jsfiddle.net/g4pr4LL9/