在javascript或jquery中单独调用特定的函数
Calling a specific function alone in javascript or jquery
我有一段这样的代码:
// 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');
}
的事情是,当点击'点击这里显示文本',它调用两个函数,并显示'文本'和'信息'。但是我不想在这里显示"info"。我不能改变HTML的div结构。
怎么做?
它在文档中有点隐藏,但是如果你看这里: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/
使用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)
});
对于原生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')
}
演示:http://jsfiddle.net/MvgTd/
无论你得到什么。
$event.stopPropagation();
相关文章:
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用