【发布时间】:2021-03-07 11:22:55
【问题描述】:
我的navigationbar 有一个单独的文件,所以当需要w3 schools include HTML 时
但它不起作用,我尝试了一切。有人可以帮我吗?
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--Media-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Title -->
<title>Cleo Boonstra</title>
<script src="IncludeHTML.js" type="text/javascript"></script>
</head>
<body>
<div include-html="NavigationBar.html"></div>
</body>
<script>
includeHTML();
</script>
</html>
在我的另一个网站上,一切正常,我只是复制了代码。
我只想让我网站的所有其他 HTML 页面在每个页面上都有相同的 navigation bar, without changing every single navigation 栏。
【问题讨论】:
-
it is not working 不是对问题的有用描述,您需要do some debugging 并在问题中报告结果。
-
在这个sn-p中不起作用,因为JavaScript是在末尾插入的,所以当你调用
includeHTML();时,它还不存在。但是在您的 HTML 中,您显示 HTML 是插入 之前includeHTML();调用,所以它应该可以正常工作。您的浏览器控制台是否显示任何错误? (顺便说一句,Java 和 JavaScript 是非常不同的语言。在 JavaScript 文件中添加.java扩展名是没有意义的。) -
也强烈建议做一个数组和一个函数。如果数组中有更多元素,则调用 succes 中的函数。不要循环 Ajax。
标签: javascript html css