【问题标题】:Calling a specific function alone in javascript or jquery在 javascript 或 jquery 中单独调用特定函数
【发布时间】:2012-12-23 17:17:53
【问题描述】:

我有一段这样的代码。

// 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 结构。

怎么做?

【问题讨论】:

  • 查找 cancelBubble() javascript 函数
  • 从你来自的元素(div)中检查类?

标签: javascript jquery html angularjs


【解决方案1】:

它在文档中有点隐藏,但如果你看这里: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/

【讨论】:

  • 哇太棒了。它真的帮助我解决了很多 pblms。非常感谢。
【解决方案2】:

使用 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)
});

【讨论】:

  • 这也与角度无关。我建议阅读他们在文档中使用 ng-click 和 Angular 完成的工作:docs.angularjs.org/api/ng.directive:ngClick
  • @MathewBerg 从未使用过 Angular js,但肯定会看到,看起来很有趣。
【解决方案3】:

对于原生 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/

【讨论】:

  • 是的,这仅在使用 var displayinfo=function 时有效。如何使它适用于 $scope.displayinfo=function()。两者都是不同的。当我尝试打印事件时,它显示未定义。
  • 这与角度无关。从内联中删除逻辑会破坏目的。
【解决方案4】:

无论你得到什么。stopPropagation(); 在你的情况下

$event.stopPropagation();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多