想象一下,我有三个文本文件html,css,javascript
HTML文件如下所示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
CSS文件如下所示
* {
box-sizing: border-box;
font-family: inherit;
}
html {
font-size: 62.25%;
}
body {
font-family: sans-serif;
font-size: 1.6rem;
}
Javascript文件如下
function hello() {
console.log("Happy Coading!!");
}
hello();
我只想返回看起来像这样的结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<style>
* {
box-sizing: border-box;
font-family: inherit;
}
html {
font-size: 62.25%;
}
body {
font-family: sans-serif;
font-size: 1.6rem;
}
</style>
<h1>Hello World</h1>
<script>
function hello() {
console.log("Happy Coading");
}
hello()
</script>
</body>
</html>
有没有办法做到这一点?我只需要尝试使用javascript中的替换功能的任何提示,但有时不起作用。
答案 0 :(得分:0)
<!DOCTYPE html>
<html>
<script>
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("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>
<body>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>
答案 1 :(得分:0)
要运行文本Javascript代码,您可以refer to this question。 我希望这会有所帮助。
谢谢。
答案 2 :(得分:0)
有时它不起作用,因为您可能已经做到了-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<!-- Here your style file -->
<link rel="stylesheet" type="text/css" href="yourstyle.css">
</head>
<script src= "myscript.js"> </script>
<body>
</body>
</html>
在这种情况下,脚本文件在文档之前加载。
因此,对于using和document元素,要么使用window.onload = function() { //write code here }
或在body标签之后编写脚本。
答案 3 :(得分:0)
将script
标记放在body标记之后:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<style>
* {
box-sizing: border-box;
font-family: inherit;
}
html {
font-size: 62.25%;
}
body {
font-family: sans-serif;
font-size: 1.6rem;
}
</style>
<h1>Hello World</h1>
</body>
<script>
function hello() {
console.log("Happy Coading"); // is this a typo?
}
hello();
</script>
</html>