我有一段这样的代码。
// HTML file
<div class="box" ng-click="displayinfo()">
click here to display info about this page.
<div class="content" ng-click="displaytext()">
Click here to display text.
</div>
click here to display info about this page.
</div>
// JS file
$scope.displayinfo = function()
{
alert('info');
}
$scope.displaytext = function()
{
alert('Text');
}
当点击“点击此处显示文本”时,它正在调用这两个函数并显示“文本”和“信息”。但我不想在这里显示“信息”。我无法改变html div结构。
怎么做?
答案 0 :(得分:2)
它在文档中有点隐藏,但如果你看一下:http://docs.angularjs.org/api/ng.directive:ngClick
您可以看到它提到$ event对象的参数。所以你的HTML会变成:
<div class="box" ng-click="displayinfo($event)">
click here to display info about this page.
<div class="content" ng-click="displaytext($event)">
Click here to display text.
</div>
click here to display info about this page.
</div>
然后你的javascript就会变成:
$scope.displayinfo = function($event)
{
$event.stopPropagation();
alert('info');
}
$scope.displaytext = function($event)
{
$event.stopPropagation();
alert('Text');
}
jsfiddle :http://jsfiddle.net/rtCP3/32/
答案 1 :(得分:1)
而是在内部调用函数使用jquery来解决这个问题:
$('.box').click(function(){
displayinfo();
});
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
displaytext();
});
e.stopPropagation()
的演示代码:http://jsfiddle.net/HpZMA/
var a = "text for info";
$('.box').click(function(){
$(this).append(a)
});
var b = "text for info";
$('.content').click(function(e){
e.stopPropagation(); //<-------------------this will stop the bubbling
$(this).append(b)
});
答案 2 :(得分:1)
对于原生javascript解决方案,您需要将event
作为参数传递给您的2种方法,以防止事件传播
<div class="box" onclick="displayinfo(event)">
然后将js更改为:
var displayinfo = function(event) {
event.cancelBubble = true
alert('info')
}
var displaytext = function(event) {
event.cancelBubble = true
alert('text')
}
答案 3 :(得分:1)
无论你得到什么.stopPropagation(); 在你的情况下
$event.stopPropagation();