输入与另一个输入的 ID 同名时的含义

Implications when an input has the same name as another input's ID

下面的脚本让我大吃一惊。它产生以下结果:

InternetExplore

aaa: undefined bbb: undefined ccc: value3 ddd: value4 eee: value5

FireFox 和 Chrome

aaa: bbb: ccc: value3 ddd: value4 eee: value5

为什么当一个输入的 ID 与另一个输入的名称相同(或相反)时,输入没有值?

function testResults(form) {
  alert([
    "aaa: " + form.aaa.value,
    "bbb: " + form.bbb.value,
    "ccc: " + form.ccc.value,
    "ddd: " + form.ddd.value,
    "eee: " + form.eee.value
  ].join(',    '));
}
<form>
  <input type="text" name="aaa" id="bbb" value="value1" />
  <input type="text" name="bbb" id="aaa" value="value2" />
  <input type="text" name="ccc" id="ccc" value="value3" />
  <input type="text" name="ddd" value="value4" />
  <input type="text" id="eee" value="value5" />
  <input type="submit" onclick="testResults(this.form)"/>
</form>

DOM 很奇怪...

但是 querySelector 会让您通过名称或 ID 获得。就像 jQuery 选择器。

form.querySelector('[name=aaa]').value
form.querySelector('#aaa').value

顺便说一句,它没有值的原因是因为 form.aaa 试图匹配 idname 和 returns 多个元素。试图获取 returns "" 的值,或者在 IE

中显然是 undefined

按名称或 ID 访问表单元素时使用的算法在 spec:

中定义

When a form element is indexed for named property retrieval, the user agent must run the following steps:

  1. Let candidates be a live RadioNodeList object containing all the listed elements whose form owner is the form element that have either an id attribute or a name attribute equal to name, with the exception of input elements whose type attribute is in the Image Button state, in tree order.

  2. If candidates is empty, let candidates be a live RadioNodeList object containing all the img elements that are descendants of the form element and that have either an id attribute or a name attribute equal to name, in tree order.

  3. If candidates is empty, name is the name of one of the entries in the form element's past names map: return the object associated with name in that map.

  4. If candidates contains more than one node, return candidates and abort these steps.

  5. Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the form element's past names map, replacing the previous entry with the same name, if any.

  6. Return the node in candidates.

具体来说,问题是 form.aaa 有两个候选项,所以 returns 一个 RadioNodeList 集合(第 4 步):

form.aaa; // RadioNodeList [ <input#bbb>, <input#aaa> ]
form.aaa[0]; // <input#bbb>
form.aaa[1]; // <input#aaa>

对于form.eee只有一个候选项,因此返回(第6步):

[=11=].eee; // <input#eee>