在javascript或jquery中单独调用特定的函数

Calling a specific function alone in javascript or jquery

本文关键字:函数 调用 单独 javascript jquery      更新时间:2023-09-26

我有一段这样的代码:

// 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();