下面的脚本让我感到惊讶。它产生以下结果:
互联网探索
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:
Let candidates be a live
RadioNodeList
object containing all the listed elements whose form owner is theform
element that have either anid
attribute or aname
attribute equal to name, with the exception ofinput
elements whosetype
attribute is in the Image Button state, in tree order.If candidates is empty, let candidates be a live
RadioNodeList
object containing all theimg
elements that are descendants of theform
element and that have either anid
attribute or aname
attribute equal to name, in tree order.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.If candidates contains more than one node, return candidates and abort these steps.
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.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/