This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
                                
                                    (8个答案)
                                
                        
                        
                            When should I use jQuery's document.ready function?
                                
                                    (8个答案)
                                
                        
                6年前关闭。
            
        

我是JavaScript和jquery的新手,想在提交之前检查表单中的字段。但是,即使从How to do something before on submit?中提取一个简单的示例也行不通。我没有在Firefox中发出警报,也没有在WebDeveloper的控制台中看到任何错误。看代码:

<html>
<head>

<script src="jquery.min.js"></script>
<script type="text/javascript">
$('#myForm').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});
</script>
</head>

<body>


<form id="myForm" action="foo.php" method="get">
   <input type="text" value="" />
   <input type="submit" value="submit form" />
</form>



</body>
</html>


当然,在同一文件夹中有“ jquery.min.js”。

最佳答案

您需要在dom准备处理程序中添加脚本

jQuery(function () {
    $('#myForm').submit(function () {
        alert('Handler for .submit() called.');
        return false;
    });
})

07-24 09:50
查看更多