美文网首页
使用jquery的load方法加载公共页面引入的js不生效

使用jquery的load方法加载公共页面引入的js不生效

作者: 高阳刘 | 来源:发表于2020-05-04 15:10 被阅读0次

每个页面的底部需要加载footer.html,在footer.js、indexhtml添加的点击事件不起作用

# footer.html
<div class="footer"></div>
# footer.js
$(function () {
    $(document).ready(function () {
        $(".com-footer").load("/footer.html");
        $(".footer").click(function(){
           console.log("footer被点击了") # 点击没反应
        })
    })
})
# index.html
<script src="/js/footer.js"></script>
<div class="com-footer"></div>
<script>
    $(".footer").click(function(){
        console.log("footer被点击了") # 点击没反应
    })
</script>

解决方法:
jQuery.getScript() 函数用于动态加载JS文件,并在全局作用域下执行文件中的JS代码。

# footer.html
<div class="footer"></div>
# footer.js
$(function () {
    $(document).ready(function () {
        $(".com-footer").load("/footer.html");
        $.getScript("/js/index.js")
    })
})
# 或者
$(function () {
    $(document).ready(function () {
        $(".com-footer").load("/html/component/footer.html", function () {
            var scriptIndex = document.createElement("script");
            scriptIndex.src = "/js/index.js";
            $("body").append(scriptIndex);
        });
    })
})
# index.html
<script src="/js/footer.js"></script>
<div class="com-footer"></div>
# index.js
$(".footer").click(function(){
    console.log("footer被点击了")
})

相关文章

网友评论

      本文标题:使用jquery的load方法加载公共页面引入的js不生效

      本文链接:https://www.haomeiwen.com/subject/qxpeghtx.html