javascript - HTMLFormElement 的操作

标签 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>

起初我使用的是 jQuery .prop() 所以我认为这是问题所在,但它也发生在纯 JavaScript 中。

我期望结果为 https://[::1]/ 但由于某种原因它给了我 [HTMLInputElement]。根据 MDN,HTMLFormElementaction 属性应该是反射(reflect) HTML action 属性的 DOMString,而不是 HTMLElement。

此行为在 Internet Explorer 和 Chrome 中都存在,因此我认为这不是浏览器实现的错误。 HTML5 specification状态:

The action IDL attribute must reflect the content attribute of the same name, except that on getting, when the content attribute is missing or its value is the empty string, the document's address must be returned instead.

我在这里遗漏了什么吗?

最佳答案

这就是specification说:

getter (RadioNodeList or Element) (DOMString name);

这意味着表单具有按名称引用每个输入元素的属性:<input name="user">会自动定义form.user 。在你的情况下,<input name="action">原因form.action要被覆盖,引用该元素而不是表单操作属性。

直接检索属性即可:

form.getAttribute("action");

或重命名您的输入:

<input name="control-action">

关于javascript - HTMLFormElement 的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25773322/

相关文章:

javascript - 没有过滤器的 AngularUI Datepicker,发生了什么?

javascript - 如何使用javascript设置css伪选择器的值?

javascript - 如何将子节点附加到特定位置

javascript - 如何提醒 Tic Tac Toe 中的获胜者?

javascript - 如何知道点击了哪个链接/按钮,然后替换内容?

javascript - js 文件未加载但执行了下一个脚本?

jQuery - 当元素从 DOM 中移除时触发事件

javascript - 如何使用 Vuejs 在 html 中显示 mysql blob 图像?

javascript - 在 tumblr 注册页面上像幽灵一样写作

javascript - 使用 capybara/selenium 访问 javascript 文件中的函数