为什么存在 document.getElementById() 函数?
创建网页时,我总是使用函数
var someVariable = document.getElementById('myID');
来获取对元素对象的引用。最近有人建议我这是没有必要的,因为已经有这样一个变量了。它的名称等于 id。我已经测试过了,它似乎有效。
<div id="myID">some text</div>
<a href="someplace" onclick="alert(myID.innerHTML)">click here</a>
此代码有效,并且它会按预期提醒“某些文本”。 Firefox 错误控制台中只有一条警告:
全局范围内 ID/NAME 引用的元素。使用 WC3 标准 document.getElementById() 代替......
我现在主要使用 jQuery,但我需要向工作中的老板证明这一点,否则我将不得不给他买一盒巧克力:-)。
任何想法为什么上面的代码不应该工作或者为什么使用它是一个非常错误的想法(Firefox 中的警告是不够的)???
感谢您的回答
when creating web pages I have always used function
var someVariable = document.getElementById('myID');
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>
This code works and it alerts "some text" as expected. There is just a warning in firefox error console:
element referenced by ID/NAME in global scope. Use WC3 standard document.getElementById() instead....
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 :-).
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)???
Thanks for your answers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为它是非标准的(但不是很长一段时间)。尽管某些浏览器确实将带有 ID 的元素分配给全局变量,但它们没有义务这样做(并非所有浏览器都这样做)。例如,旧版本的 Firefox 不会表现出这种行为。还存在命名冲突的风险。
使用
document.getElementById()
确保所有浏览器在获取元素句柄时的行为完全相同(嗯,或多或少咳)。请参阅 bobince 对以下问题的出色回答类似的问题以获取更多信息。
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.
Using
document.getElementById()
ensures that all browsers behave exactly the same (well, more or less cough) when getting a handle to an element.See bobince's excellent answer to a similar question for more information.
您当前的调用可能会导致变量冲突。
想象一下:
myID
现在不是您的 HTML 元素,而是一个包含 '富'。 示例。您应该始终使用 document.getElementById(),因为它是为特定功能构建的检索 HTML 元素而不是 JavaScript 变量。
Your current call would result in possible variable collision.
Picture this:
myID
is now not your HTML element, but a variable containing 'foo'. Example.You should always use document.getElementById() because it is built for the specific function to retrieve HTML elements and not JavaScript variables.
推测是为了跨浏览器兼容性。第二个版本在 Chrome 中不起作用。这意味着它在 Safari 中也可能会失败。
Presumable for cross browser compatibility. The second version doesn't work in Chrome. Which mean it would probably fail in Safari as well.