[英]how to make button clickable but its parent div?
I am trying to trigger a function when a button inside a div is clicked and another function when the div is clicked.When I am clicking the button
div
is also getting clicked.how to make div
not clickable when button is clicked 我试图在单击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>
You will want to use event.stopPropagation()
, this will stop the click bubbling up to its containers. 您将要使用
event.stopPropagation()
,这将使单击停止冒泡至其容器。
https://developer.mozilla.org/en/docs/Web/API/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>
You need to stop the event propagation. 您需要停止事件传播。
Change your button function to this: 将按钮功能更改为此:
$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>
You can use event
object(e) and use it's target
property to determine the click
event is invoked by which element. 您可以使用
event
对象(e)并使用它的target
属性来确定由哪个元素调用click
事件。
$("div").on("click", function(e)
{
var target = $(e.target);
if(target.is('button'))
alert('button clicked');
});
Example : https://jsfiddle.net/g4pr4LL9/ 范例: https : //jsfiddle.net/g4pr4LL9/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.