本文介绍了具有相同名称的表单元素反映在DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在表单中有多个具有相同的名称的表单元素,则元素集合中的条目该表格最终是这些字段的集合(这是方便的)。 DOM2 HTML规范,但是当有多个具有相同名称的字段时,不会立即显示此行为。行为是否符合标准(DOM2 HTML规范中的某个地方或另一个规范)?

If you have multiple form elements with the same name in a form, the entry in the elements collection on the form ends up being a collection of those fields (which is handy). The DOM2 HTML specification covers the elements collection but doesn't immediately seem to specify this behavior when there are multiple fields with the same name. Is the behavior covered by a standard (somewhere else in the DOM2 HTML specification, or in another spec)?

为了清楚起见,我不是问最好的方法访问这些字段是。我问是否在元素集合中收集(不同种类)的事实是由标准覆盖的,如果是这样的话。

For clarity, I'm not asking what the best way to access these fields is. I'm asking whether the fact they end up in a collection (of varying kinds) on the elements collection is covered by a standard, and if so which one.

示例():

HTML:

<form id="theForm">
<input type="text" name="foo" value="one">
<input type="text" name="foo" value="two">
</form>

JavaScript:

JavaScript:

var form = document.getElementById("theForm"),
    foo = form.elements.foo,
    index;
console.log("typeof foo = " + typeof foo);
if (typeof foo !== "undefined") {
  console.log("Object#toString says: " + Object.prototype.toString.call(foo));
}
if ('length' in foo && 'item' in foo) {
  console.log("Looks like a collection of some kind:");
  for (index = 0; index < foo.length; ++index) {
    console.log(index + ": " + foo[index].value);
  }
}

输出样本(适用于Chrome):

Sample output (for Chrome):

typeof foo = object
Object#toString says: [object NodeList]
Looks like a collection of some kind:
0: one
1: two

我检查过IE6,7,8和9,Firefox 4.0,Firefox 3.6,Chrome 12,Opera 11,和Safari 5.他们都在元素中输入一些类型的集合(Chrome,Firefox和Safari使它成为一个 NodeList [虽然奇怪的是Safari上的 typeof 是function而不是object],IE和Opera使它成为一个 HTMLCollection ,但它们都有长度项目 [] 访问)。我只是试图找到指定行为的标准(如果有的话)。

I've checked IE6, 7, 8, and 9, Firefox 4.0, Firefox 3.6, Chrome 12, Opera 11, and Safari 5. They all make the entry in elements a collection of some kind (Chrome, Firefox, and Safari make it a NodeList [though bizarrely on Safari the typeof is "function" not "object"], and IE and Opera make it an HTMLCollection, but they all have length, item, and [] access). I'm just trying to find the standard, if any, that specifies the behavior.

推荐答案

HTML5规范草案(和WHAT-WG版本),在这种情况下,似乎更多地关于记录它总是如何工作,在 HTMLFormControlsCollection (,):

It's covered by the draft HTML5 spec (and the WHAT-WG version), which in this case seems more about documenting how it’s always worked, under the section on HTMLFormControlsCollection (W3C ref, WHAT-WG ref):

这篇关于具有相同名称的表单元素反映在DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:12