如何解决包含在另一个 HTML 页面中的 HTML 页面的脚本不起作用,如何解决?
在开发网站的过程中,我在一个单独的 HTML 文件 (nav.html) 中创建了一个导航栏,我可以将其加载到任何我想在 Javascript 中使用 AJAX 调用的页面。问题是当导航栏加载到实际页面中时,此导航栏中包含的脚本不会运行。 (但是导航栏在页面中正确加载)
nav.html
<div id= topnav class="topnav">
<...html...>
</div>
<script>
console.log("THIS WON'T GET PRINTED OUT")
</script>
page.html
<html>
<nav id="nav"></nav>
</html>
<script>
loadTopBar()
function loadTopBar(){
var xhr= new XMLHttpRequest();
xhr.open('GET','static/getnavbar',true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementById('nav').innerHTML= this.responseText;
};
xhr.send();
}
</script>
解决方法
将您希望能够在函数中调用的任何代码括起来,并在成功加载 AJAX 结果后调用该函数。
此外,不要检查 readystate
和 status
并在它们不是您想要的时返回,而是在它们出现时继续。
nav.html
<div id= topnav class="topnav">
<...html...>
</div>
<script>
// Code that is not inside of a function should be avoided so that
// you can more precisely control when and how often it executes.
function foo(){
console.log("THIS WON'T GET PRINTED OUT");
}
</script>
page.html
<html>
<nav id="nav"></nav>
</html>
<script>
loadTopBar()
function loadTopBar(){
var xhr= new XMLHttpRequest();
xhr.open('GET','static/getnavbar',true);
xhr.onreadystatechange= function() {
if (this.readyState===4 && this.status ===200){
document.getElementById('nav').innerHTML= this.responseText;
foo(); // <-- Call the function that should now be available
}
};
xhr.send();
}