为什么 Jquery 表单提交事件没有触发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18734357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why Jquery form submit event not firing?
提问by Kshitij Jain
I am trying to submit a form through jquery. I want to get my form submit event get fired when jquery submits the form.
我正在尝试通过 jquery 提交表单。我想让我的表单提交事件在 jquery 提交表单时被触发。
But when form is submitted successfully, submit event handler is not called successfully.
但是当表单提交成功时,提交事件处理程序不会成功调用。
Below is the code :
下面是代码:
<html>
<head>
<title>forms</title>
<script src="../common/jquery-1.6.2.min.js"></script>
<script>
$('#testform').submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(html) {
$("#menu").html('<object>'+html+'</object>');
});
return false; // prevent normal submit
});
</script>
</head>
<body>
<form id="testform" action="<%=getURL%>" method="post" >
<!-- <input type="hidden" value="DocQrySetup" name=form>
<input type="hidden" value="bdqdb1" name=config>-->
<input type="hidden" value="test" name=otherParams>
</form>
<script language=javascript>
$('#testform').submit();
</script>
<div id="menu" style="position:relative; bottom: 0; overflow:hidden;">
</div>
</body>
I searched all the forums but was not able to get the resolution.
我搜索了所有论坛,但无法获得解决方案。
回答by Dave Forber
The form doesn't exist when you run the first script so your event handler has nothing to attach to.
当您运行第一个脚本时该表单不存在,因此您的事件处理程序没有任何可附加的内容。
Either need to move that handler to after the form or wrap it in
要么需要将该处理程序移动到表单之后或将其包装在
$(document).ready(function() {
$('#testform').submit(function() {
/* your code */
});
});
回答by Emil A.
The form isn't defined when you attach the event listener, move the code where you attach the event listener after the form or wrap the code with:
附加事件侦听器时未定义表单,将代码移动到表单后附加事件侦听器的位置或将代码包装为:
jQuery(document).ready(function ($) {
...
});
And add a submit button.
并添加一个提交按钮。
...
<input type="submit" value="submit">
...