我需要通过 native javascript(不是 jQuery)选择一个表单并阻止表单提交(preventDefault)。
诀窍在于表单没有名称或 ID,也无法分配。
我的 HTML:
<div id="search">
<form method="get">
<input type="text" name="post"/>
<input type="submit" value="Post">
</form>
</div>
到目前为止,我已尝试使用 document.forms[0]
和 document.getElementsByTagName("form")[0]
来选择表单,但是返回值未定义。
另一种可能的解决方案是重载提交按钮的功能,但我也没有成功。
最佳答案
使用 querySelector
和一个事件监听器,它几乎就像 jQuery
document.querySelector('#search form').addEventListener('submit', function(e) {
e.preventDefault();
});
请注意,脚本必须位于元素之后,或者使用 DOM 就绪处理程序,以便元素可用。
关于javascript - 停止使用 native javascript 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27514097/