javascript - 当一个输入与另一个输入的 ID 具有相同名称时的含义

标签 javascript html forms dom

下面的脚本让我感到惊讶。它产生以下结果:

互联网探索

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>

最佳答案

通过名称或 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 有两个候选者,因此它返回 RadioNodeList收集(第 4 步):

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

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

$0.eee; // <input#eee>

关于javascript - 当一个输入与另一个输入的 ID 具有相同名称时的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29198899/

相关文章:

javascript - Web应用程序的移动应用程序(离线存储)

javascript - setTimeout() 返回未捕获的类型错误

javascript - AngularJS 中 JSON 和 HTML 标签的日期格式

html - Chrome 63+ 抛出 [DOM] 错误,输入类型密码和非唯一 ID

javascript - 使用 Enter 键移动到输入

javascript - 从多个表单中获取输入来打印答案(Javascript)

css - 重力形式 选择占位符样式

javascript - 带有选择器的 jQuery next() 没有根据类找到指定的元素

javascript - Child_process 抛出错误 : write EPIPE

java - 如何使用 Selenium WebDriver 选择组合框值,其中它是具有组合框角色的 div