有没有一个规范,元素的id应该成为全局变量? [英] Is there a spec that the id of elements should be made global variable?

查看:128
本文介绍了有没有一个规范,元素的id应该成为全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Chrome中有一个< div id ='a'> ,那么在javascript中我可以执行 a。 () (就好像 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)

另外,我有兴趣Chrome如何解决歧义,如果我有一个div的ID a 还在我的脚本中有一个名为 a 的全局变量。这个行为会是随机的吗?

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 访问,但是浏览器将如何将其转换为代表它们的全局变量) p>

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规范描述(cf, http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id 和< a href =http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name> http://www.w3.org/TR/1999/REC-html401 -19991224 / types.html#类型名称)。但是,它是由Internet Explorer引入的,然后在其他主要浏览器中复制以兼容。 FireFox还会显示此行为,但仅在怪异模式中(甚至其实现似乎很差)。

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规范目前为需要这种行为,但是有一个打开的错误请求将其删除

The WHATWG HTML spec currently requires this behavior but there is an open bug requesting that it be removed.

无论规范合规性,使用全局命名空间(即窗口)用于应用程序代码通常被认为是坏的行为。考虑使用 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邮件列表

这篇关于有没有一个规范,元素的id应该成为全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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