直接引用HTML元素

时间:2011-10-19 19:08:17

标签: javascript html

  

可能重复:
  IE/Chrome: are DOM tree elements global variables here?
  why window[id] === document.getElementById( id )

我刚刚在html / javascript中遇到过一些让我感到惊讶的事情。当获得对html元素的引用时,使用javascript,我以前总是使用jQuery或document.getElementById。您还可以使用它的id直接访问元素。有人可以解释这个细微差别吗?我用Google搜索但找不到任何关于此功能的引用,每个网站都会讨论getElementById。

以下页面摘录说明了这一点。

<html>
<head>
</head> 
<body>
    <input type="button" value="getElement" onclick="document.getElementById('blah').innerText = 'getElementById'" />
    <input type="button" value="direct" onclick="blah.innerText = 'direct';" />
    <div id="blah"></div>
</body>

非常感谢提前。

3 个答案:

答案 0 :(得分:14)

能够根据[id]选择页面上的元素是早期JavaScript的一个“功能”(DOM lvl 0或1个methinks,似乎无法找到源代码)。

不幸的是,这是一种气质特征。如果您有以下情况会发生什么:

<div id="window"></div>

<div id="document"></div>

更好的是,这里发生了什么?

<div id="foo"></div>
<div id="bar"></div>
<script>var foo = document.getElementById('bar');</script>

因此基于它[id]调用元素的细微差别就是这样:

不要使用它。

不一致,也不保证会得到未来的支持。

就我个人而言,我希望看到这个“功能”符合document.all的方式。它只会导致比它解决的问题更多的问题,而document.getElementById虽然确实冗长,但却是有意义且可以理解的。

答案 1 :(得分:2)

使用getElementById更灵活,更易读。例如,这不起作用:

<input type="button" value="direct" onclick="document.innerText = 'direct';" />
<div id="document"></div>

原因很明显,但这会:

<input type="button" value="getElement" onclick="document.getElementById('document').innerText = 'getElementById'" />
<div id="document"></div>

并且其他开发人员更清楚这是什么。

答案 2 :(得分:0)

我不相信它是一个记录的功能,它似乎不适用于Firefox(6),但它似乎适用于最新版本的Chrome,以及IE 6-9。

我不会依赖它,只会将其视为浏览器功能的奇特之处。