JavaScript文档.write不工作

JavaScript document.write is not working

本文关键字:工作 write 文档 JavaScript      更新时间:2023-09-26

很抱歉,如果这看起来很愚蠢,我是JavaScript新手。

这是在menu.js:中

document.write("<a href="index.html">Home</a>");
document.write("<a href="news.html">News</a>");
document.write("<a href="about.html">About us</a>");

这是在index.html:中

<head>
</head>
<body>
    <script type="text/javascript" src="menu.js"></script>
</body>
</html>

当我加载index.html时,什么都不会出现。。。

问题是您的引号,您使用"来分隔新元素并设置其href属性,请将代码更改为:

document.write("<a href='index.html'>Home</a>");
document.write("<a href='news.html'>News</a>");
document.write("<a href='about.html'>About us</a>");

或者:

document.write('<a href="index.html">Home</a>');
document.write('<a href="news.html">News</a>');
document.write('<a href="about.html">About us</a>');

组合单引号(')和双引号(")。你也可以逃避你的内部报价(document.write("<a href='"index.html'">Home</a>");

但最好使用对document.write()的单个调用,如下所示:

document.write('<a href="index.html">Home</a>' 
    + '<a href="news.html">News</a>'
    + '<a href="about.html">About us</a>');

您不会转义字符串中的引号。应该是:

document.write("<a href='"index.html'">Home</a>");

否则,JavaScript认为字符串在href=之后结束,并且该行的其余部分不遵循有效的JavaScript语法。

正如@Felix所提到的,JavaScript调试器工具将非常有助于让您了解发生了什么。