Jquery脚本没有在angular包含的html文件中运行

时间:2016-02-18 14:59:16

标签: jquery html angularjs

我有这个非常简单的jquery脚本:

$(document).ready(function() {

    $("h2").click(function(){
        alert("Hello world");
    })    
});

当我点击整个网站上的任何h2时,会显示一条警告。

当我在我的index.html中放置一个h2时,这很好用但是当我把h2放在angular包含的一些文件中时,当我点击h2时没有任何反应。

这些是我的文件

index.htm
included.htm
myjqueryfunctions.js

以下是我如何包含jquery文件

<body>
.... some code ....
<script src="jquery_functions.js"></script>
</body>

以下是我使用angular

包含HTML文件的方法
<div ng-include src=" 'included.htm' "></div>

其他一切都很好。

问题:为什么我的jquery-script在我的index.html中放入h2时工作正常,但是当它放在included.html

1 个答案:

答案 0 :(得分:1)

您好,您应该按以下方式调用选择

 // This WILL work because we are listening on the 'document', 
    // for a click on an element with an tag h2
    $(document).on('click',"h2", function(){
            alert("Hello world");
        })  

    // This will NOT work because there is no 'h2' (added later or injected by angular)... yet
    $("h2").on("click",function() {
        alert("hello");
    });