JQuery侦听表单提交事件

JQuery侦听表单提交事件,jquery,html,forms,Jquery,Html,Forms,在过去的几个小时里,我一直在努力工作,我似乎无法让一个简单的JQuery提交操作侦听器工作。以下是我使用的代码: <form id="hello-world" action="sayhello"> <input type="submit" value="Hello!"> </form> <script type="text/javascript"> $('#hello-world').submit(function(ev) {

在过去的几个小时里,我一直在努力工作,我似乎无法让一个简单的JQuery提交操作侦听器工作。以下是我使用的代码:

<form id="hello-world" action="sayhello">
    <input type="submit" value="Hello!">
</form>
<script type="text/javascript">
    $('#hello-world').submit(function(ev) {

        ev.preventDefault(); // to stop the form from submitting
        alert("form submitted");
    });  
</script>
点击Hello!按钮,则不显示警报,并且该操作已执行,即我的浏览器尝试加载localhost/sayhello


有人知道发生了什么吗?

它可能试图在元素准备就绪之前附加事件。确保在DOM完全加载后附加处理程序

$(function() {
    $('#hello-world').submit(function(ev) {

        ev.preventDefault(); // to stop the form from submitting
        alert("form submitted");
    });
});

看起来可能是其他原因,例如jquery没有加载?控制台中是否有其他错误

您的代码可以在JSFIDLE上完美运行,无需任何更改:


因此,在提交事件中,您正试图停止提交。这似乎有些可疑。试试点击。效果很好-。您可能还没有包括jQuery库,请检查您的控制台。@user3237539谢谢您的帮助-原来我在javascript函数之后包括了jQuery…谢谢您的回复-原来我有一个高级时刻,Jquery只是在我的脚本之后才被收录…@RTUR很高兴我能帮上忙谢谢你的回复-原来我有一个高级时刻,Jquery只是在我的脚本之后才被收录。。。我会记住你关于检查文档的提示。不过要记住!
<form id="hello-world" action="sayhello">
    <input type="submit" value="Hello!">
</form>
<script type="text/javascript">
    $('#hello-world').submit(function(ev) {

        ev.preventDefault(); // to stop the form from submitting
        alert("form submitted");
    });  
</script>