Javascript:为什么在js中仍然存在getElementById(id)的元素? [英] Javascript: Why get an element with getElementById(id) when it is still present in js?

查看:72
本文介绍了Javascript:为什么在js中仍然存在getElementById(id)的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我注意到,引用一个具有id的html元素可以通过javascript访问,只需一个名为id的变量( jsbin )。



为什么会这样?为什么要使用 getElementById(id)而不是简单地写 id

解决方案


为什么会这样?




因为早期的浏览器是这样做的,它是现在变成标准化


为什么我们必须使用 getElementById(id) 而不是简单地编写id?


从技术上讲,你不会。但请注意,全球命名空间真的非常拥挤。那里有一大堆东西。不仅仅是具有ID的元素,而是某些元素,如果它们具有 name s,浏览器上下文的名称等,这意味着可能会有冲突。例如,如果您有一个 id =document的元素,则不会创建自动全局。其他冲突的全局变量可能因浏览器而异。另外, id 值无效的JavaScript标识符(如 id =foo-bar)仍然完美有效的 id 值,但它的全局自动( window [foo-bar] )使用起来很尴尬



使用 getElementById 特别寻找 ID / strong> 1 (不是名称等)。所以它更加包含和可靠。






1 忽略过时版本的错误IE,没有正确地约束它。


Lately i noticed that a reference to a html element with an id can be accessed by javascript simply with a variable named like that id (jsbin).

why is this so? why do we have to even use getElementById(id) instead of simply writing id?

解决方案

why is this so?

Because early browsers did that, and it's now become standardized.

why do we have to even use getElementById(id) instead of simply writing id?

Technically, you don't. But beware that the global namespace is really, really crowded. There's a whole bunch of stuff thrown in there. Not just elements with IDs, but certain elements if they have names, the browser context by name, etc., etc., which means there can be conflicts. For instance, if you had an element with id="document", the automatic global won't be created. The other, conflicting globals can vary by browser. Also, id values that aren't valid JavaScript identifiers (like id="foo-bar") are still perfectly valid id values, but the automatic global for it (window["foo-bar"]) is awkward to use.

Using getElementById specifically looks for an element with that ID1 (not name, etc.). So it's more contained and reliable.


1 Ignoring bugs in obsolete versions of IE, which failed to constrain it correctly.

这篇关于Javascript:为什么在js中仍然存在getElementById(id)的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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