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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:41:02  来源:igfitidea点击:

How to remove existing and add onsubmit in form using jquery

javascriptjquery

提问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 onsubmitfunction?

是否可以更改表单的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 unbindfunction, eg:

您可以使用 jQuery 的unbind函数删除现有事件,例如:

$('#myForm').unbind('submit');

will remove all onsubmitevents from #myForm. Then you can add a new event using normal jQuery:

将从中删除所有onsubmit事件#myForm。然后你可以使用普通的 jQuery 添加一个新事件:

$('#myForm').submit(function(e) { /* your logic here */ });