在 php 中我这样写:
<?php include "file.php" ?>
在 html 文件中,我这样写:
<script src='file.js'></script>
现在,我正在处理一个 js 文件。
在这个 js 文件中,我想包含这样的 html 文件。
<script>
code to include html file here
code to include html file here
code to include html file here
code to include html file here
code to include html file here
code to include html file here
code to include html file here
</script>
非常感谢。
最佳答案
您不能在外部 JS 文件中调用 HTML 文件,但您可以为此创建一个辅助函数。
Following this tutorial你将能够得到这样的东西:
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 = "filename.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.";}
//elmnt.innerHTML - THIS HTML FROM YOUR FILE
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
关于javascript - 如何在js文件中包含html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607495/