AngularJS模板中jQuery的单击事件不触发 [英] jQuery click events not firing within AngularJS templates

查看:559
本文介绍了AngularJS模板中jQuery的单击事件不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是有点在那里从来没有人经历过这种奇怪的情况,但我在场外的机会张贴这一点,有人知道的东西我不知道。

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-包括属性,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>

这也与使用的使用模板指令的情况。这是奇怪的,并造成了我很多麻烦一些下拉菜单。

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就绪不可用 - 而这是通过推入DOM角加载时 template.html - 你需要使用的,而不是使用。点击 jQuery的事件代表团:

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 类元素的click事件。

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

这篇关于AngularJS模板中jQuery的单击事件不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆