jQuery 单击事件未在 AngularJS 模板中触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18876537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:40:32  来源:igfitidea点击:

jQuery click events not firing within AngularJS templates

jqueryangularjs

提问by Adam K Dean

This may be a bit of strange case where nobody has ever experienced this before, but I'm posting this on the off-chance that somebody knows something I don't.

这可能是一个奇怪的案例,以前没有人经历过这种情况,但我发布此消息是因为有人知道我不知道的事情。

I'm using jQuery 2.0.3 and AngularJS.

我正在使用 jQuery 2.0.3 和 AngularJS。

If I have an anchor in index.htmllike so:

如果我有这样的锚点index.html

# index.html
<a href="#" class="clickme">Click Me</a>

<script type="text/javascript">
$(function() {
    $('.clickme').click(function() { console.log("click"); });
});
</script>

Then it works, and when I click it, it outputs 'click'. But when I put that inside a template that I include with the ng-includeattribute, the jQuery all of a sudden doesn't fire. If I place the script inside the template with the anchor though, it DOES fire.

然后它工作,当我点击它时,它输出“点击”。但是当我把它放在一个包含ng-include属性的模板中时,jQuery 突然不会触发。如果我将脚本放在带有锚点的模板中,它确实会触发。

# index.html
<div ng-include="'path/to/template.html'"></div>

# template.html
<a href="#" class="clickme">Click Me</a>

<script type="text/javascript">
$(function() {
    $('.clickme').click(function() { console.log("click"); });
});
</script>

This is also the case with using directives which use templates. It's bizarre and causing me a lot of hassle with some drop down menus.

使用模板的 using 指令也是如此。这很奇怪,给我一些下拉菜单带来了很多麻烦。

Does anyone know why this is happening?

有谁知道为什么会这样?

回答by CodingIntrigue

Since your clickmeprobably isn't available on DOM ready - rather it is pushed into the DOM by Angular when it loads template.html- you need to use jQuery's event delegation instead of using .click:

由于您clickme可能在 DOM 就绪时不可用 - 而是在加载时由 Angular 将其推送到 DOM template.html- 您需要使用 jQuery 的事件委托而不是使用.click

$(document).on("click", ".clickme", function() {
  console.log("click");
});

This will ensure jQuery binds onto the document, then monitors for any click events on elements with the clickmeclass.

这将确保 jQuery 绑定到文档,然后监视具有clickme该类的元素上的任何单击事件。