javascript变量对应于具有相同ID的DOM元素 [英] javascript variable corresponds to DOM element with the same ID

查看:72
本文介绍了javascript变量对应于具有相同ID的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,我刚刚注意到一个JavaScript行为,我没有看到记录在任何地方。如果我有一个具有分配ID的DOM元素,说x,那么在我的javascript中,该元素被自动分配给变量x。我在chrome和safari看到这个。这是javascript的记录功能吗?

I am new to javascript, and I just noticed a javascript behavior that I haven't seen documented anywhere. If I have a DOM element with an assigned id, say "x", then in my javascript, that element is automatically assigned to variable x. I see this in chrome and safari. Is this a documented feature of javascript?

例如:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id='x'>
<input type='text' name='info' id='info'/>
<input type='submit' name='submit' value='Complete'/>
</form>
<script type='text/javascript'>
  window.onload = function() {
    alert( x==document.getElementById('x') );
    info.value = 'Test me!';
  }
</script>
</body>
</html>

加载时,它将提醒true,输入区域将显示Test me!。如果这是正确的行为,为什么我们需要document.getElementById?

When loaded, it will alert true, and the input area will show 'Test me!'. If this is the right behavior, why do we need document.getElementById at all?

推荐答案

这个行为记录在 HTML标准(第6.2.4节)

该标准定义了命名元素,它们是具有名称 id 属性集。 (请注意,名称属性仅在某些类型的HTML元素上定义。)

The standard defines "named elements" which are HTML elements that have either a name or id attribute set. (Note that the name attribute is only defined on certain types of HTML elements.)

对于每个命名元素,浏览器(环境)定义相应的全局属性。

For each named element, the browser (environment) defines a corresponding global property.

这篇关于javascript变量对应于具有相同ID的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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