JavaScript document.write 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18276223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript document.write is not working
提问by Maria Ines Parnisari
Sorry if this seems dumb, i'm new to JavaScript.
对不起,如果这看起来很愚蠢,我是 JavaScript 的新手。
This is in menu.js
:
这是在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>");
This is in index.html
:
这是在index.html
:
<head>
</head>
<body>
<script type="text/javascript" src="menu.js"></script>
</body>
</html>
When I load index.html
, nothing comes up...
当我加载时index.html
,什么也没有出现......
回答by DarkAjax
The problem is your quotes, you're using "
both to delimit your new elements and to set their href
attribute, change your code to:
问题是您的引号,您"
同时使用它们来分隔新元素并设置它们的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>");
Or:
或者:
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>');
Combining single ('
) and double ("
) quotes. You could also escape your internal quotes (document.write("<a href=\"index.html\">Home</a>");
结合单 ( '
) 和双 ( "
) 引号。您也可以转义内部引号 (document.write("<a href=\"index.html\">Home</a>");
BUT it'd be better to use a single call to document.write()
, like this:
但是最好使用单个调用document.write()
,如下所示:
document.write('<a href="index.html">Home</a>'
+ '<a href="news.html">News</a>'
+ '<a href="about.html">About us</a>');
回答by Jrop
You're not escaping the quotes in your strings. It should be:
您没有转义字符串中的引号。它应该是:
document.write("<a href=\"index.html\">Home</a>");
Otherwise, JavaScript thinks the string ends after href=
and the rest of the line does not follow valid JavaScript syntax.
否则,JavaScript 认为字符串在此之后结束,href=
并且该行的其余部分不遵循有效的 JavaScript 语法。
As @Felix mentioned, the JavaScript debugger tools will be extremely helpful in letting you know what's going on.
正如@Felix 所提到的,JavaScript 调试器工具将非常有助于让您了解正在发生的事情。