直接引用HTML元素 [英] Directly reference HTML elements

查看:108
本文介绍了直接引用HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

IE / Chrome:DOM树元素全局变量在这里?

为什么窗口[id] === document.getElementById(id)

我刚刚在html / javascript中遇到过一些让我感到意外的东西。当使用javascript获取html元素的引用时,我以前一直使用jQuery或document.getElementById。它似乎也可以简单地通过使用它的id来直接访问元素。有人可以解释这个细微差别吗?我已经使用了Google搜索功能,但是找不到任何有关此功能的参考信息,因此每个网站都会讨论getElementById。



以下页面片段说明了这一点。

 < html> 
< head>
< / head>
< body>
< input type =buttonvalue =getElementonclick =document.getElementById('blah')。innerText ='getElementById'/>
< input type =buttonvalue =directonclick =blah.innerText ='direct'; />
< div id =blah>< / div>
< / body>



非常感谢。 / p>

解决方案可以根据 [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 ,当然是冗长的,是有意义的和可以理解的。


Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
why window[id] === document.getElementById( id )

I've just come across something in html/javascript which has surprised me a bit. When obtaining a reference to an html element, using javascript, I have always previously used either jQuery or document.getElementById. It also appears that you can directly access a element simply by using it's id. Can someone explain the nuances of this? I've googled but cannot find any reference to this ability, every site talks about getElementById.

The following page snippet illustrates this.

<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>

Many thanks in advance.

解决方案

Being able to select elements on the page based on their [id] is a "feature" from early JavaScript (DOM lvl 0 or 1 methinks, can't seem to find the source).

Unfortunately it's a temperamental feature. What would happen if you had:

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

or

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

Better yet, what happens here?

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

So the nuances to calling an element based on it's [id] is simply this:

Don't use it.

It's not consistent, and not guaranteed to receive future support.

Personally I'd like to see this "feature" go the way of document.all. It only causes more issues than it solves, and document.getElementById, while certainly verbose, is meaningful and understandable.

这篇关于直接引用HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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