为什么jQuery .submit不起作用?

adi*_*dis 2 jquery form-submit

在提交表单之前,我试了几乎一个小时来弄清楚如何进行一些验证.我的表格是这样的:

<!doctype html>
<head>
<title>sample</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">      </script>
<script>
 $("#myform").submit(function() {
   alert("it is not working");
   return false;
 });
</script>
</head>
<body>
  <form id="myform">
   <input id="foo" value="Change me and press enter"/>
   <input type="submit" />
  </form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

它不适用于IE,Chrome FF :-(我必须做一些非常错误的事情,但是什么?

编辑

工作样本:

<!doctype html>
<head>
<title>sample</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script>
    $(document).ready(function() {
    $("#myform").submit(function() {
        alert("Now it is def working!");
        return false;
    });
});
</script>
</head>
<body>
<div id="myform">
<form id="myform">
    <input id="foo" value="Change me and press enter"/>
    <input type="submit" />
</form>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Nea*_*eal 16

将它包装在就绪功能中:

$(function(){
   $("#myform").submit(function() {
      alert("THIS IS WORKING!!!!!!");
      return false;
   });
});
Run Code Online (Sandbox Code Playgroud)

您需要将它包装在ready函数中,因为现在您的函数所在,DOM元素#myForm不存在,因此您将处理程序附加到不存在的元素.

ready函数等待DOM加载,然后运行ready ready中的所有内容.