JavaScript document.write无效

时间:2013-08-16 14:54:10

标签: javascript document.write

很抱歉,如果这看起来很愚蠢,我是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时,什么都没有出现......

2 个答案:

答案 0 :(得分:8)

问题在于您的引号,您使用"来分隔新元素并设置其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>');

答案 1 :(得分:2)

您没有转义字符串中的引号。它应该是:

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

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

正如@Felix所提到的,JavaScript调试器工具对于让您了解正在发生的事情非常有帮助。