javascript 如何使用jquery在表单中删除现有并添加onsubmit
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7008043/
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
How to remove existing and add onsubmit in form using jquery
提问by mymotherland
Given this HTML to create a form:
给定这个 HTML 来创建一个表单:
<form name="search" id="myForm" onsubmit="return existingfunc()" method="post">
<input type="submit" value="Search" title="Search">
</form>
I can change the form's name via jQuery using $('#myForm').attr('name','newname')
.
我可以通过 jQuery 使用$('#myForm').attr('name','newname')
.
Is it possible to change the form's onsubmit
function?
是否可以更改表单的onsubmit
功能?
回答by Jeromy French
To just change the form onsubmit event you could do this:
要更改表单 onsubmit 事件,您可以执行以下操作:
$('#myForm').attr('onsubmit', 'return somethingElse()');
But you probably want to removethe form's onsubmit attribute then add a new eventusing jQuery (note: unbind()
will remove only event handlers attached by jQuery):
但是您可能想要删除表单的 onsubmit 属性,然后使用 jQuery添加一个新事件(注意:unbind()
将仅删除由 jQuery 附加的事件处理程序):
$('#myForm').removeAttr('onsubmit').submit(function(e) { /* your logic here */ });
回答by beeglebug
You can remove an existing event using jQuery's unbind
function, eg:
您可以使用 jQuery 的unbind
函数删除现有事件,例如:
$('#myForm').unbind('submit');
will remove all onsubmit
events from #myForm
. Then you can add a new event using normal jQuery:
将从中删除所有onsubmit
事件#myForm
。然后你可以使用普通的 jQuery 添加一个新事件:
$('#myForm').submit(function(e) { /* your logic here */ });