为什么document.getElementById()函数存在? [英] Why does document.getElementById() function exist?

查看:116
本文介绍了为什么document.getElementById()函数存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建网页时我总是使用函数

when creating web pages I have always used function

var someVariable = document.getElementById('myID');

获取对元素对象的引用。最近有人向我建议这不是必要的,因为已经存在这样的变数。它的名字等于id。我已经测试了它似乎有效。

to get a reference to an element object. It was recently suggested to me that this is not necessary, because there already is such a variable. It's name is equal to the id. I've tested it and it seems to work.

<div id="myID">some text</div>
<a href="someplace" onclick="alert(myID.innerHTML)">click here</a>

此代码有效,它会按预期警告某些文字。 firefox错误控制台中只有一个警告:

This code works and it alerts "some text" as expected. There is just a warning in firefox error console:


在全局范围内由ID / NAME引用的元素。使用WC3标准document.getElementById()而不是....

element referenced by ID/NAME in global scope. Use WC3 standard document.getElementById() instead....

我现在主要使用jQuery,但我需要证明一点我的老板在工作,否则我将不得不给他买一盒巧克力:-)。

I am mostly using jQuery by now but I need to prove a point to my boss at work or else I will have have to buy him a box of chocolate :-).

任何想法为什么上面的代码不起作用或为什么使用它是一个非常错误的想法(在Firefox中警告是不够的)???

Any ideas why the upper code shouldnt work or why is it a very wrong idea to use it(warning in firefox is not enough)???

感谢您的回答

推荐答案


任何想法为什么高级代码不起作用或为什么使用它是一个非常错误的想法(在Firefox中警告是不够的)???

Any ideas why the upper code shouldnt work or why is it a very wrong idea to use it(warning in firefox is not enough)???

因为这是非标准的(但不适用于长)。虽然某些浏览器确实将带有ID的元素分配给全局变量,但它们没有义务这样做(并不是所有的都这样做)。例如,旧版本的Firefox不会出现此行为。还存在命名冲突的风险。

Because it's non-standard (but not for long). Although some browsers do assign elements with an ID to global variables, there's no obligation for them to do so (and not all of them do). Older versions of Firefox, for instance, do not exhibit this behavior. There's also the risk of naming collisions.

使用 document.getElementById()确保获取元素句柄时,所有浏览器的行为都完全相同(好吧,或多或少 cough )。

Using document.getElementById() ensures that all browsers behave exactly the same (well, more or less cough) when getting a handle to an element.

参见关于类似问题的优秀答案以获取更多信息。

这篇关于为什么document.getElementById()函数存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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