是否有规范将元素的 id 设为全局变量?

如果我在 Chrome 中有一个 <div id='a'> 然后在 javascript 中我可以执行 a.stuff()(就像 a 是一个全局变量一样).

If I have a <div id='a'> in Chrome then in javascript I can do a.stuff() (it's like as if a is a global variable).

但这不适用于 FireFox - 我需要使用 document.getElementById('a').

However this does not work with FireFox - I will need to use document.getElementById('a').

这里的正确行为是什么?(根据 W3 规范)

What is the correct behaviour here? (according to W3 specs that is)

此外,如果我有一个 ID 为 a 的 div,但在我的脚本中也有一个名为 a 的全局变量,那么我对 Chrome 将如何解决歧义感兴趣.这种行为会是随机的和古怪的吗?

Also I'm interested in how will Chrome resolve the ambiguity if I have a div with id a yet have a global variable called a too in my script. Is the behavior going to be random and whacky?

以及如何翻译 id 由连字符 ("-")、冒号 (":") 和句点 (".") 组成的元素(好的,我知道它们可以通过 document.getElementById 访问 但浏览器如何将其转换为代表它们的全局变量)

And how would an element with id consisting of hyphens ("-"), colons (":"), and periods (".") be translated (ok i know they can be accessed with document.getElementById but how will the browser translate it into the global variable that was representing them)

推荐答案

这取决于您阅读的规范.:)

It depends on which spec you read. :)

HTML4 规范未描述此行为(参见 http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id 和 http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name).但是,它是由 Internet Explorer 引入的,然后为了兼容而复制到其他主要浏览器中.FireFox 也显示此行为,但仅在 quirks mode (即便如此,它的实现似乎也有问题).

This behavior is not described by the HTML4 specification (c.f., http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id and http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name). However, it was introduced by Internet Explorer and then copied in other major browsers for compatibility. FireFox also displays this behavior, but only in quirks mode (and even then its implementation seems buggy).

WHATWG HTML 规范目前要求 这种行为(bug 报告要求将其删除已关闭 WONTFIX).

The WHATWG HTML spec currently requires this behavior (a bug report requesting it be removed was closed WONTFIX).

无论是否符合规范,对应用程序代码使用全局命名空间(即 window)通常被认为是不良行为.考虑使用 document.getElementById() 或 jQuery 便利方法(例如,$("#a"))引用元素 ID,并使用函数范围的变量来避免引入新的变量到全局命名空间中.

Regardless of spec compliance, using the global namespace (i.e., window) for application code is generally considered bad behavior. Consider referencing element IDs using document.getElementById() or jQuery convenience methods (e.g., $("#a")) and using function-scoped variables to avoid introducing new variables into the global namespace.

WHATWG 邮件列表.

相关文章