【问题标题】:jQuery Delegate Event STILL not triggered for element in AngularJS templateAngularJS模板中的元素仍未触发jQuery委托事件
【发布时间】:2020-10-23 23:18:38
【问题描述】:

我知道很多帖子都在谈论使用jQuery Delegate Event 来解决 AngularJS 模板中的点击事件,但这对我来说根本不起作用:

在我的app.js

jQuery.noConflict();

(function ($) {
   // My Angular code is here:
   // var app = angular.module("myApp", ["ngRoute", "firebase"])
   // Bla bla bla...

   $(".bordered-button-red .show-guide-button").on("click", function () {
       alert("Clicked!");
   });
})(jQuery);

我什至尝试过以下方法,但都没有奏效:

$(document).on("click", ".bordered-button-red .show-guide-button", function () {
    alert("Clicked!");
});

虽然我认为我的查询选择器是错误的,但下面也不起作用:

// No space between .bordered-button-red and .show-guide-button    
$(".bordered-button-red.show-guide-button").on("click", function () {
    alert("Clicked!");
});

以下是我的模板:

<div ng-controller="myCtrl">
   <div class="bordered-button-red show-guide-button">Show Guide</div>
   <p>Guide text...</p>

   <div class="bordered-button-red show-guide-button">Show Guide</div>
   <p>Different guide text...</p>

   <div class="bordered-button-red show-guide-button">Show Guide</div>
   <p>Another guide text...</p>

</div>

如您所见,我有多个指南按钮和同一组文本,所以我更喜欢使用 jQuery(而不是 ng-clickng-show),以便我可以利用 $(this) 和 @987654330 @如下图:

$(".bordered-button-red .show-guide-button").on("click", function () {
    alert("Clicked!");
    
    if ($(this).text() == "Show Guide") {
        $(this).next().show();
        $(this).text("Hide Guide");
    } else {
        $(this).next().hide();
        $(this).text("Show Guide");
    };
});

使用ng-clickng-show 对于这样一个简单的任务来说工作量太大了,尤其是当您还想像在jQuery 中那样简单地向显示/隐藏中添加动画 时: show("slow")。我试图将myCtrl 放入app.js 中,但也没有工作。知道如何让我的 jQuery 委托事件真正起作用吗?

非常感谢您!

注意:对于上述任何试验,控制台均未记录任何 javascript 错误。

【问题讨论】:

  • 如果你只是想实现一个显示/隐藏的效果,你真的不需要使用jQuery。
  • 你用的是什么版本的jquery?
  • @angel.bonev : &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt;
  • 您是否尝试过将点击事件委托给正文?可能是文档防止冒泡。
  • @skobaljic :像魅力一样工作!我已经在下面发布了答案!非常感谢!

标签: jquery angularjs


【解决方案1】:

正如 @skobaljic 所评论的,委托点击body 工作:

$("body").on("click", ".bordered-button-red.show-guide-button", function () {
        alert("Clicked!");
        
        if ($(this).text() == "Show Guide") {
            $(this).next().show();
            $(this).text("Hide Guide");
        } else {
            $(this).next().hide();
            $(this).text("Show Guide");
        };
    });

但请注意,jQuery 选择器两个类之间不得有空格".bordered-button-red.show-guide-button"。再次感谢@skobaljic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多