在 javascript 中,这是一个有效的构造吗?:document.name.name.value? [英] In javascript is this a valid construct?: document.name.name.value?

查看:26
本文介绍了在 javascript 中,这是一个有效的构造吗?:document.name.name.value?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

表格如下:

<form name=fname ...
   <input name=iname value="" ...

这个javascript函数获取输入的值:

This javascript function obtains the value of the input with:

var val = document.fname.iname.value;

这合法吗?我认为您必须使用 getElementsByName 来执行此操作.它有效,只是我从未见过有人这样做.这是目前碰巧起作用的事情之一吗?

Is that legit? I thought you had to do this with getElementsByName. It works, it's just I've never seen anyone do it that way. Is this one of those things that just happens to work... for now?

推荐答案

UPDATE

根据 WHATWG 6.2.4 Window 对象的命名访问

Window 对象支持命名属性.Window 对象窗口在任何时候支持的属性名称包括以下内容,...对于所有 appletembedformframesetimgobject 元素...

The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following,...for all applet, embed, form, frameset, img, and object elements...


根据 W3C DOM 2 HTML 规范 2.7.2.1 HTMLAllCollection

以下元素名称属性可以作为文档对象的属性引用:anchorappletbuttonformframeiframeimginputmapmetaobjectparamselecttextarea

The following elements name attribute can be referenced as a property of the document object: anchor, applet, button, form, frame, iframe, img, input, map, meta, object, param, select, and textarea


这种引用方法是标准的,但通常不鼓励使用.避免通过 name 属性直接引用 DOM 属性或窗口对象的几个原因是:变量阴影、无意中将范围限定到窗口对象、主要的浏览器不一致等.有关为什么应该避免这种情况的详细信息,请阅读本节这篇文章.


This referencing approach is standard, but it's use is generally discouraged. A few reasons to avoid directly referencing DOM property or window object by name attributes are: variable shadowing, inadvertently scoping to the window object, major browser inconsistencies, etc. For details on why it should be avoided, read this section and this post.

此代码段展示了使用表单名称作为参考的稳定且标准的方式 document.forms 以及前面提到的引用表单名称.

This Snippet shows a stable and standard way of using form names as a reference document.forms and the referencing form names previously mentioned as well.

var val1 = document.forms.fname.elements.iname.value;

console.log(val1);

var val2 = fname.iname.value;

console.log(val2);

<form name='fname'>
   <input name='iname' value="42">
</form>

这篇关于在 javascript 中,这是一个有效的构造吗?:document.name.name.value?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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