javascript - 停止使用 native javascript 提交表单

标签 javascript html forms submit

我需要通过 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 就绪处理程序,以便元素可用。

FIDDLE

关于javascript - 停止使用 native javascript 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27514097/

相关文章:

javascript - 检查是否使用 jQuery 选择了选项,如果没有选择默认值

html - 应用样式表后两个按钮(超链接、提交)大小不一样

html - 在框架内居中图像 - 没有javascript

javascript - AngularJS 选择 |从 JSON 中选择一个 id 后显示该 id 的其余信息

javascript - jQuery 不更改 Internet Explorer 中的类或 CSS

javascript - 除了我可以评估的之外,这个 javascript 是否有任何合乎逻辑的目的?

html - 如何使用填充将图像定位在文本旁边?

javascript - 显示/隐藏以前的表单字段条目

html - 如何从 <option><select> 传递值以形成操作

javascript - Selenium /Java : How to write element locator for an element with aria-selected=false