我为我的网站创建了一个主菜单(html和css),每次编辑菜单时将其复制/粘贴到网站的每个文件/页面中是荒谬的,我需要它自动出现在每个文件/页面上单个文件。
如何在我的网站中重复使用/包含此主菜单?
我已经尝试过使用 jquery 和 ajax 进行一些操作,但没有成功。我最后尝试的是这样的:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("#").innerHTML = this.responseText;
}
};
xhttp.open("GET", "my_file_menu.html", true);
xhttp.send();
}
最佳答案
您始终可以使用 AJAX/fetch 加载文件,并在加载后使用 DOM 操作将其添加到文档中。但我猜您可能只想使用一个简单的库来完成此操作。
看看w3.js and the w3.includeHtml() function 。它使用起来非常简单,不需要学习模板或 View 框架,例如 react 。这是一个例子:
main-page.html
<!DOCTYPE html>
<html>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<body>
<div w3-include-html="main-menu.html"></div>
<script>
w3.includeHTML();
</script>
</body>
</html>
main-page.html
<ul>
<li><a href='home'>Home</a></li>
<li><a href='contact'>Contact Us</a></li>
</ul>
关于javascript - 如何在网站中重复使用重复的 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479569/