我可以在JavaScript中使用HTML元素的ID作为变量吗? [英] Can I use the id of an HTML element as a variable in JavaScript?

查看:106
本文介绍了我可以在JavaScript中使用HTML元素的ID作为变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

偶然,我注意到我可以在JavaScript代码中使用HTML元素的 id 。所以不是这样的:

  var myCanvas = document.getElementById('myCanvas'); 
myCanvas.width ='600';
myCanvas.height ='400';

我可能根本就没有第一行,因为变量 myCanvas 显然已经存在!

  myCanvas.width ='600'; 
myCanvas.height ='400';

这很好,但我可以依靠它吗?这是我在所有现代浏览器中可以预期的正常行为吗?我不介意IE9之前的任何浏览器。 https://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here#answer-3434388 \">answer 并提及这是不是 标准行为。所有浏览器都支持此行为(不包括quircks模式下的Firefox),但我不推荐使用它。 在标准模式下 firefox< 14 不支持 strong>


Accidentally, I noticed I could use the id of an HTML element in JavaScript code. So instead of this:

var myCanvas = document.getElementById('myCanvas');
myCanvas.width = '600';
myCanvas.height = '400';

I could simply not even have the first line, because the variable myCanvas apparently already exists!

myCanvas.width = '600';
myCanvas.height = '400';

This is nice, but can I rely on it? Is this normal behavior that I can expect in all modern browsers? I don't care about any browsers before IE9.

解决方案

I'm going to refer you to this answer and mention that this is not standard behaviour. This behaviour is supported by all browsers (sans Firefox outside of quircks mode) but I would not recommend its use. This is not supported by firefox<14 in standards mode

这篇关于我可以在JavaScript中使用HTML元素的ID作为变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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