简体   繁体   English

当javascript在元素上调用提交时,jQuery覆盖表单提交不起作用

[英]jQuery override form submit not working when submit called by javascript on a element

I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. 我有一个带有提交按钮的正常表单的页面和一些绑定到表单提交事件的jQuery,并用e.preventDefault()覆盖它并运行一个AJAX命令。 This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' 单击提交按钮但是当链接与onclick='document.formName.submit();'时,这样可以正常工作 is clicked, the event is not caught by the AJAX form submit event handler. 单击,AJAX表单提交事件处理程序不会捕获该事件。 Any ideas why not or how to get this working without binding to all the a elements? 任何想法为什么不能或如何在不绑定所有元素的情况下使其工作?

A couple of suggestions: 一些建议:

  • Overwrite the submit function to do your evil bidding 覆盖提交功能以进行恶意出价

    var oldSubmit = form.submit;
    form.submit = function() {
        $(form).trigger("submit");
        oldSubmit.call(form, arguments);
    }
  • Why not bind to all the <a> tags? 为什么不绑定到所有<a>标签? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag): 然后你不必做任何猴子修补,它可以像(假设所有链接都在form标签内)一样简单:

    $("form a").click(function() {
        $(this).parents().filter("form").trigger("submit");
    });

If you are using jQuery, you should be attaching events via it's own event mechanism and not by using "on" properties (onclick etc.). 如果您使用的是jQuery,则应该通过它自己的事件机制附加事件,而不是使用“on”属性(onclick等)。 It also has its own event triggering method, aptly named ' trigger ', which you should use to activate the form submission event. 它还有自己的事件触发方法,恰当地命名为' trigger ',您应该使用它来激活表单提交事件。

Thanks Eran 谢谢伊兰

I am using this event binding code 我正在使用此事件绑定代码

this._form.bind('submit', Delegate.create(this, function(e) {
    e.preventDefault();
    this._searchFadeOut();
    this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));
});

but there is legacy onclick code on the HTML and I would prefer not to change it as there are just so many links. 但HTML上有遗留的onclick代码,我宁愿不改变它,因为有这么多的链接。

This worked for me: 这对我有用:

Make a dummy button, hide the real submit with the name submit, 制作一个虚拟按钮,隐藏真实提交,名称提交,

and then: 然后:

$("#mySubmit").click(function(){
    $("#submit").trigger("click"); });

set an event handler on your dummy to trigger click on the form submit button. 在您的虚拟对象上设置一个事件处理程序,以触发单击表单提交按钮。 let the browser figure out how to submit the form... This way you don't need to preventDefault on the form submit which is where the trouble starts. 让浏览器弄清楚如何提交表单...这样你就不需要在表单提交上preventDefault ,这是麻烦开始的地方。

This seemed to work around the problem. 这似乎解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM