在JavaScript块中的HTML评论? [英] HTML comments in a javascript block?

查看:96
本文介绍了在JavaScript块中的HTML评论?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的函数(下面),它在HTML页面中插入一段HTML代码:

 函数someEventHandler(htmlContent)
{
document.getElementById('some-element-id')。innerHTML = htmlContent;
}

这适用于包含 img的HTML代码标记



当HTML代码包含< script> 他们不渲染。此外,脚本块包含由HTML注释包围的JavaScript。例如:

 < script type =text / javascript> 
<! -
function someFunctionThatRendersStaticImageOrFlash()...
- >
< / script>

包含HTML注释的这些脚本块在插入后不会呈现。我控制了插入的代码,并且在没有HTML注释的情况下对它进行了测试,并且它们已成功呈现。



我的理解是,这样的HTML注释被用于早期版本的Netscape,以防止浏览器与javascript不兼容的问题。

是否有任何其他原因(或任何理由)在JavaScript块中包含HTML样式注释?



编辑
错误。关闭评论是: // - >

解决方案

实际上,只有<! - 是有效的javascript。要在javascript中结束html注释,实际上需要使用 // - >

现在,不再需要在Javascript中使用HTML注释。如果浏览器太旧以至于无法理解< script> 标签,则很难在现代网站上呈现大部分内容,而且您不应该不得不容忍真正在石器时代浏览器上使用的用户。



但是,如果您打算将HTML包含在xml文档中,并且/或者编写x-html,那么你必须使用xml <![CDATA []]> & ,< ,和> )将导致XML解析错误,而不包含该机箱。


I have a function like this one (below) which inserts a block of HTML code in an HTML page:

function someEventHandler(htmlContent)
{
  document.getElementById('some-element-id').innerHTML = htmlContent;
}

This works fine for HTML code that includes an img tag.

When the HTML code includes <script> blocks, though, they do not render. Furthermore, the script blocks contain JavaScript that is surrounded by HTML comments. For example:

<script type="text/javascript">
<!--
    function someFunctionThatRendersStaticImageOrFlash()...
-->
</script>

These script blocks that contain HTML comments do not render after they have been inserted. I have control over the code that is inserted and I tested it without the HTML comments, and they rendered successfully.

It is my understanding that HTML comments like this were used in early versions of Netscape, to prevent problems with browser incompatibility with javascript.

Is there any other reason (or any good reason) to include HTML style comments in a javascript block?

Edit I mistyped. The closing comment is: //-->.

解决方案

Actually, only <!-- is valid javascript. To end the html comment in javascript, you actually need to use //-->.

These days it's not really required to use the HTML comments in Javascript anymore. Browsers which are so old as to not understand the <script> tag are highly unlikely to be able to render much of anything on a "modern" website, and you should not have to accommodate users who are quite literally on a stone-age browser.

However, if you're intending to include your HTML inside an xml document, and/or are writing x-html, then you'll have to use the xml <![CDATA[ and ]]> enclosures, as various Javascript operators (&, <, and > in particular) will cause XML parse errors without the enclosures.

这篇关于在JavaScript块中的HTML评论?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆