简体   繁体   English

为什么 document.write("-->") 没有按预期工作?

[英]Why document.write("-->") does not work as expected?

<p>hello</p>
<script type="text/javascript">
document.write("<!--");
</script>
<p>world</p>
<script type="text/javascript">
document.write("-->");
</script>
<p>nihao</p>

I thought the output of this piece of HTML is我认为这段 HTML 的输出是

hello
nihao

But it turns out as below:但结果如下:

hello
");
nihao

How should I achieve what I expected?我应该如何实现我的预期? What's the problem here?这里有什么问题?

Well, the first JavaScript element is executed which leads to a representation like this:好吧,第一个 JavaScript 元素被执行,这导致了这样的表示:

<p>hello</p>
<!--
<p>world</p>
<script type="text/javascript">
document.write("-->");
</script>
<p>nihao</p>

So the HTML comment start you just added spans into your next JavaScript element and the resulting output is just as you described.因此,您刚刚添加的 HTML 注释开始跨度到您的下一个 JavaScript 元素中,结果输出就像您描述的那样。 To answer your second question, whats wrong with the following?要回答你的第二个问题,以下内容有什么问题?

<p>hello</p>
<script type="text/javascript">
document.write("<!--<p>world</p>-->");
</script>
<p>nihao</p>

It is because the <!-- in your javascript is parsed as the start of a comment before the JavaScript runs.这是因为在 JavaScript 运行之前,您的 JavaScript 中的<!--被解析为注释的开始。

There have been some useful answers, but if you actually want to create a comment and insert it into your document then you need to use the createComment() function :已经有一些有用的答案,但如果你真的想创建评论并将其插入到你的文档中,那么你需要使用createComment()函数

var comment = document.createComment("This is a comment") 
​document.appendChild(comment);​

Will output:将输出:

<!--This is a comment-->

To get exactly result you expect:要获得您期望的准确结果:

<p>hello</p>
<script id="ahh" type="text/javascript">
document.write("<!"+"--"+"<p>world<p>--"+">");
document.getElementById('ahh').remove()
</script>
<p>nihao</p>​

anyway it is pretty bad idea.无论如何,这是一个非常糟糕的主意。

If, like me, you came across this question wanting to hide an element when JavaScript is enabled, consider using the <noscript> tag instead!如果你像我一样遇到这个问题,想在启用 JavaScript 时隐藏元素,请考虑使用<noscript>标签!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM