为什么我不能在HTML标签内插入评论?

为什么我不能在HTML标签内插入评论?

问题描述:

我有什么理由不能在HTML标签内插入注释?

Are there any reason why I can't insert a comment inside the HTML tag?

示例:以HTML格式显示(不可能)

 <img <!-- sample comment--> src="" alt="Sample Picture" class="img-circle center-block" />

使用JavaScript可以轻松完成.

While in JavaScript it can be easily done.

示例:在JS中(可能)

verticalCentered: /* Sample Comment*/ true

请详细解释.

HTML最初被正式定义为SGML的应用程序,而注释语法则取自SGML.SGML使用两个连字符-作为注释定界符,但仅允许在某些上下文中使用注释.在这些上下文中,只有注释声明与HTML有关.(嗯,从理论上讲,它们也可以在<!ENTITY foo"foo"-注释-> 之类的实体声明中允许使用,但是在XHTML之前的任何浏览器中,以及XHTML,遵循XML语法,实体声明不能包含注释.)

HTML was originally defined formally as an application of SGML, and the comment syntax was taken from SGML. SGML uses two hyphens -- as comment delimiters, but it permits comments in certain contexts only. Of these contexts, only a comment declaration is relevant in HTML. (Well, in theory they are also allowed in entity declarations like <!ENTITY foo "foo" -- Comment -- >, but entity declarations were never implemented in any browser before XHTML, and in XHTML, following XML syntax, entity declarations cannot contain comments.)

因此,仅允许在注释中只包含注释的注释声明中使用注释,例如

Thus, comments are only allowed in comment declarations that contain nothing but comments, e.g.

<!-- Comment one -- -- Comment two -->

浏览器实际上以简化(错误)的方式部分实现了此功能,因此实际建议是仅在包含单个注释的注释声明中包含注释:

Browsers actually implemented this partly in a simplified (wrong) way, so the practical recommendation is to have comments only in comment declarations that contain a single comment:

<!-- Comment -->

注释声明与标签处于相同的结构级别,因此不能出现在标签内.(注释也不能包含标签:否则会构成标签的任何内容,例如< p> ,都将在注释内用作字符数据.)

Comment declarations are at the same structural level as tags and therefore cannot appear within tags. (Comments cannot contain tags either: anything that would otherwise constitute a tag, like <p>, is taken just as character data when inside a comment.)

在更高的HTML版本中未对此进行更改.他们在这种情况下简化了语法,没有扩展.

This has not been changed in later HTML versions. They have simplified the syntax in matters like this, not extended.