Javascript HTMLFormElement的操作
下面是重现问题的HTML片段:Javascript HTMLFormElement的操作,javascript,html,dom,forms,Javascript,Html,Dom,Forms,下面是重现问题的HTML片段: <form id=foo action='https://[::1]/'> <input type=hidden name=action value=xyz> </form> <script> window.alert(document.getElementById('foo').action); </script> window.alert(document.getElementB
<form id=foo action='https://[::1]/'>
<input type=hidden name=action value=xyz>
</form>
<script>
window.alert(document.getElementById('foo').action);
</script>
window.alert(document.getElementById('foo').action);
起初我使用的是jQuery.prop()
,所以我认为这就是问题所在,但在纯JavaScript中也是如此
我希望结果是https://[::1]/
,但出于某种原因,它给了我[HTMLInputElement]
。根据MDN,的action
属性应该是反映HTMLaction
属性的DOMString,而不是HTMLElement
这种行为在InternetExplorer和Chrome中都存在,所以我认为这不是浏览器实现中的错误。各国:
action
IDL属性必须反映同名的content属性,但在获取时,当content属性丢失或其值为空字符串时,必须返回文档的地址
我在这里遗漏了什么吗?使用
在您的示例中,之所以会发生这种情况,是因为表单中有一个子元素,其属性为“action”。JS正在为您的表单返回一个HTMLCollection,.action
是该表单的子节点。形式是特殊的
重命名它以查看原始JS是否按预期工作:
<form id=foo action='https://[::1]/'>
<input type=hidden name=definitelyNOTaction value=xyz>
</form>
以下是
这意味着表单具有按名称引用每个输入元素的属性:
将自动定义表单。用户
。在您的情况下,
会导致覆盖form.action
,引用该元素而不是form-action属性
只需直接检索属性:
form.getAttribute("action");
或重命名您的输入:
<input name="control-action">
这并不能回答我的问题……请澄清你的问题。在你的帖子中唯一的一个是“我在这里遗漏了什么吗?”我认为这是一个修辞,但要回答它。。。是的,我的问题是为什么会这样happen@rink.attendant.6使访问表单元素更容易。我们还没有像querySelector
这样的方法,但是当他们编写这个规范时。。。
form.getAttribute("action");
<input name="control-action">