是否有规范元素的 id 应该设为全局变量? [英] Is there a spec that the id of elements should be made global variable?

查看:23
本文介绍了是否有规范元素的 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-idhttp://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-name).但是,它是由 Internet Explorer 引入的,然后为了兼容性而复制到其他主要浏览器中.FireFox 也会显示此行为,但仅限于 quirks 模式(即便如此,它的实现似乎也有问题).

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 规范目前需要 此行为(错误 报告要求将其删除已关闭 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 邮件列表.

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

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