我真的需要调用getElementById()吗? [英] do I really need to call getElementById()?

查看:55
本文介绍了我真的需要调用getElementById()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

我在浏览器中偶然发现了一个意外但有用的行为:它为我的html代码中具有ID的每个元素创建一个变量。所以当我有:

I just stumbled upon an unexpected but useful behavior in the browser: It creates a variable for every element that has an ID in my html code. So when I have:

<div id="ohlala"> ... </div>

浏览器似乎在幕后运行此代码:

the browser seem to run this code behind the scene:

var ohlala = document.getElementById("ohlala");

所以我可以通过以下方式轻松更改该元素的文本:

so I can easily change the text of that element by:

ohlala.innerHTML="test"

在线试用: http://jsfiddle.net/Facby/
问题是:为什么我需要自己编写 document.getElementById()位?该代码的可移植性如何?我在Opera,FireFox和Chrome上试过,它有效!我可以依靠这个功能吗?浏览器是否总是为每个具有id的元素创建变量?在这种情况下,我必须更加小心我的javascript代码中使用的名称不要与HTML中的类似ID冲突,对吗?

Try it online: http://jsfiddle.net/Facby/ The question is: why would I need to write the document.getElementById() bit myself? How portable is that code? I tried in Opera, FireFox and Chrome and it works! Can I rely on this functionality? Does the browser always create variables for every element with id? In that case I have to be more careful about the names that are used in my javascript code not to conflict with similar ids from the HTML, right?

推荐答案

当使用ID创建元素时,window对象接收特定属性,这就是您可以直接使用变量的原因,这种行为已被弃用,通常写成如下: window.ohlala .innerHTML =...,浏览器为了与网站上的一些旧代码兼容而保留此行为,但不建议在现代网站中使用它,始终使用.getElementById()方法,这个方法是W3C标准的一部分,你可以在所有现代浏览器中使用它,在一些非常古老的浏览器版本和< IE7它无法正常工作。在此处了解有关DOM(文档对象模型)的更多信息: https://developer.mozilla.org/ en-US / docs / DOM

When creating elements with IDs, the "window" object receives the specific attributes, that's why you can use variables directly, this behavior is deprecated and usually is wrote like this: window.ohlala.innerHTML = "...", this behavior is conserved by the browsers for compatibility with some older code on websites, but it is not recommended to use it in modern websites, always use .getElementById() method, this method is part of a W3C Standard, and you can use it in all modern browsers, in some very old browser versions and < IE7 it will not work. Learn more about DOM (Document Object Model) here: https://developer.mozilla.org/en-US/docs/DOM

这篇关于我真的需要调用getElementById()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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