gpt4 book ai didi

javascript - getElementById 没有按预期工作?

转载 作者:行者123 更新时间:2023-12-03 11:27:00 26 4
gpt4 key购买 nike

我有这个simple HTML 标记:

<form id="form" action="lalala">
<input type="text" id="action"/> //a reserved property name id
<input type="submit" id="submit"/> //same here
</form>

但是——运行:

alert(document.getElementById('form').action);

提醒

enter image description here

而不是它应该的“lalala”。

好像getElementById的props不是直接访问的

这是为什么呢? ..... 这实际上意味着我必须知道所有表单元素的 Prop (为了不向后代元素提供保留的 Prop ID)?

最佳答案

这与 getElementById 无关,与 HTML 表单元素对象的属性有关。

a reserved property name id

它不是“保留的”,它只是有一个默认定义的值

如果您在表单中有一个表单控件,并且该控件的 ID(或名称)与表单元素所具有的属性相匹配,那么对该表单控件的引用将覆盖该属性的正常值。

When a form element is indexed for indexed property retrieval, the user agent must return the value returned by the item method on the elements collection, when invoked with the given index as its argument.

http://www.w3.org/TR/html5/forms.html#the-form-element

这很糟糕,但是自从出现这样的东西以来,表单的 DOM 就是这样工作的。

由于该特定属性映射到属性值,您可以使用 getAttributesetAttribute 来操纵它。 (这在旧 IE 中不起作用(它对那些对属性进行操作的方法的实现已损坏)并且不适用于其他一些属性(如提交方法))。

it can actually mean that I have to know all the form element's props (in order not to provide reserved prop ID to a descendant element)

是的。

关于javascript - getElementById 没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398151/

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