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

查看:34
本文介绍了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 章).

该标准定义了命名元素",即具有 nameid 属性集的 HTML 元素.(请注意,name 属性仅在某些类型的 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天全站免登陆