仅将模态保留在一个位置(引导)



我正在使用引导程序构建一个网站,我必须在每个页面上使用相同的模式。现在我必须将整个代码复制到每个 html 中,然后它可用于每个页面,但这不是理想的做事方式,所以我希望有人向我建议一种方法,我不必将相同的 html 代码复制到每个文件。我想要一种方法,即相同的html代码可用于所有页面,而它只保存在一个地方。 我不能在这里发布我的代码,但我会尝试准确地告诉你我的问题。

<!-- navbar for website -->
1 html code
<!-- sign in and login modal(buttons are on navbar) -->
2 html code
<!-- main body -->
3 html code
4 html code
5 html code
<!-- footer for website -->
6 html code
7 html code

例如,根据上面的块导航栏,每个页面的模态和页脚(1,2,6,7行(保持不变。我怎么能把所有这些放在其他地方,然后以某种方式链接它,就像链接css文件一样(类似的东西(。我可以给你更多信息,只是在评论中询问(除了我的确切代码(。

有两种方法可以实现您的目标:

  1. 使用Javascript

<script>
function includeModal() {
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("w3-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("w3-include-html");
includeHTML();
}
} 
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>

然后调用它

<script>
includeModal();
</script>

  1. 使用 HTML

<div w3-include-html="modal.html"></div>

首先,您需要划分 html,例如仅为页脚制作另一个文件,即页脚.html和页眉.html等。

然后使用 JQuery 包含它们。

<html> 
<head> 
<script src="jquery.js"></script> 
<script> 
$(function(){
$("#includedContent").load("header.html"); 
});
</script> 
</head> 
<body> 
<div id="includedContent"></div>
</body> 
</html>

jQuery .load(( 文档在这里

最新更新