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

このHTMLの出力は

hello
nihao

しかし、以下のようになります。

hello
");
nihao

期待したことをどのように達成すればよいですか?ここで何が問題なのですか?

4

5 に答える 5

8

Well, the first JavaScript element is executed which leads to a representation like this:

<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. 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>
于 2012-12-09T21:30:41.033 に答える
5

これは<!--、JavaScript が実行される前に、JavaScript の がコメントの開始として解析されるためです。

于 2012-12-09T21:24:59.563 に答える
5

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:

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

Will output:

<!--This is a comment-->
于 2012-12-09T21:32:27.687 に答える
2

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.

于 2012-12-09T21:31:04.810 に答える