getElementById和简单地使用元素的ID作为变量有什么区别? [英] What is the difference between getElementById and simply using an element's ID as a variable?
问题描述
有人能告诉我调用id =myDomObect的HTML元素之间的区别吗?:
Can someone tell me the difference between calling an HTML elment with id="myDomObect"?:
var myObj = document.getElementById('myDomObect');
&
var myObj = myDomObect;
推荐答案
使用第一个表格或一个包装,如jQuery。第二种形式,
Use the first form or a wrapper such as jQuery. The second form,
var myObj = myDomObect;
转换为
var myObj = window["myDomObect"];
这个有效是因为旧的,旧的黑客,其中ID是被曝光为全局窗口属性(IIRC从一开始就是错误的),因此我们仍然很幸运20年后的行为......是的,它将在最新的Chrome中工作。
This "works" because of an old, old hack in which ID's were exposed as global window properties (IIRC this was a misfeature from the start) and thus we are still blessed with the behavior 20 years later.. and yes, it will work in the very latest Chrome.
但是,出于多种原因
However, such a shorthand should not be used for multiple reasons:
-
它不会像最初用严格模式那样工作(但它可以使用第二种形式)
It will not work as originally written in "strict mode" (but it will work with the second form)
它不传达操作 - 即请求/获取DOM元素(通过ID)。
It does not convey the operation - namely that a DOM element is requested/fetched (by ID).
它不适用于与窗口属性冲突的ID;例如。如果以这种方式访问,< div id = history>< / div>
会导致意外行为。 (这不会影响在函数中正确使用本地 var
变量的getElementById代码。)
It does not work for IDs that collide with window properties; eg. <div id=history></div>
would result in "unexpected behavior" if accessed this way. (This doesn't affect getElementById code that correctly uses local var
variables in a function.)
当文档中存在重复ID( 允许)时,未定义行为;为的getElementById的行为已经被DOM 4编入:的getElementById(elementId)方法必须以树的顺序返回第一个元素[带有ID]。
Behavior is not defined when duplicate IDs exist in the document (which is allowed); the behavior for getElementById has been codified in by DOM 4: "getElementById(elementId) method must return the first element [with the ID], in tree order.."
参见:
See also:
- Do DOM tree elements with ids become global variables?
这篇关于getElementById和简单地使用元素的ID作为变量有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!