jQuery 单击事件未在 AngularJS 模板中触发 [英] jQuery click events not firing within AngularJS templates
问题描述
这可能是一个有点奇怪的案例,以前没有人经历过这种情况,但我发布此消息是因为有人知道我不知道的事情.
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.
我使用的是 jQuery 2.0.3 和 AngularJS.
I'm using jQuery 2.0.3 and AngularJS.
如果我在 index.html
中有一个锚点,如下所示:
If I have an anchor in index.html
like so:
# index.html
<a href="#" class="clickme">Click Me</a>
<script type="text/javascript">
$(function() {
$('.clickme').click(function() { console.log("click"); });
});
</script>
然后它就工作了,当我点击它时,它输出点击".但是,当我将其放入包含 ng-include
属性的模板中时,jQuery 突然不会触发.如果我将脚本放在带有锚点的模板中,它确实会触发.
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-include
attribute, the jQuery all of a sudden doesn't fire. If I place the script inside the template with the anchor though, it DOES fire.
# 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>
使用模板的 using 指令也是如此.这很奇怪,给我一些下拉菜单带来了很多麻烦.
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.
有人知道为什么会这样吗?
Does anyone know why this is happening?
推荐答案
因为您的 clickme
可能在 DOM 就绪时不可用 - 而是在加载 template.html
- 你需要使用 jQuery 的事件委托,而不是使用 .click
:
Since your clickme
probably 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
:
$(document).on("click", ".clickme", function() {
console.log("click");
});
这将确保 jQuery 绑定到文档,然后使用 clickme
类监视元素上的任何点击事件.
This will ensure jQuery binds onto the document, then monitors for any click events on elements with the clickme
class.
这篇关于jQuery 单击事件未在 AngularJS 模板中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!