我知道很多帖子都在谈论使用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-click
和ng-show
(,以便我可以利用$(this)
和.next()
如下所示:
$(".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-click
和ng-show
工作量太大,尤其是当您还想像 jQuery:show("slow")
中那样简单地向显示/隐藏添加动画时。我试图把app.js
myCtrl
里面,但也没有用。知道我怎样才能让我的 jQuery 委托事件真正工作吗?
提前非常感谢!
注意:对于上述任何试用,控制台中均未记录任何 JavaScript 错误。
正如@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!