gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:04:47 26 4
gpt4 key购买 nike

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

互联网探索

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com