每个页面的底部需要加载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被点击了")
})
网友评论