防止一个表单提交并提交另一个表单 - 此方法是否可靠? [英] Preventing one form submission, and submitting another - is this approach reliable?

查看:146
本文介绍了防止一个表单提交并提交另一个表单 - 此方法是否可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否安全 - 在一个表单的提交事件处理程序中 - 提交另一个表单并返回 false 以防止提交第一个表单?

  $(#form1)。submit(function(){
$(#form2)。submit();
返回false;
});

我正在使用这种方法,它起作用(至少在IE6中)。但是,我担心这可能不适用于其他浏览器。可以调用 submit 以某种方式取消返回false 吗?



我正在考虑的另一种方法是

$ $ p $ $(#form1)。submit(function(){
setTimeout('$(#form2)。submit();',10);
return false;
});

....但是这可能会增加复杂性,因为实际上并不需要。



需要这样做的原因是用户正在提交 form1 ,但是在某种情况下(我可以检测到JavaScript)这是一个错误,可以通过在 form2 的字段之一中设置一些数据,然后提交这个表单来改正。

解决方案

你的代码应该适用于所有的浏览器,但是如果你想确保你能做到的话。

  $(#form1)。submit(function(evt){
evt.preventDefault(); //取消默认行为
$( #form2)。submit();
return false;
});

使用 .preventDefault() 方法可确保您在之前取消默认行为它..


Is it safe to - within a submit event handler for one form - submit another form and return false to prevent the submission of the first form?

$("#form1").submit(function() {
    $("#form2").submit();
    return false;
});

I am using this approach, and it works (in IE6 at least). However, I am concerned that this might not work in other browsers. Could the call to submit cancel out the return false somehow?

The alternative approach I was considering is

$("#form1").submit(function() {
    setTimeout('$("#form2").submit();', 10);
    return false;
});

....but this might well be adding complexity where none is actually needed.

The reason for needing to do this is that the user is submitting form1, but in a certain scenario (which I can detect using JavaScript) this is causing a bug, that can be rectified instead by setting some data in one of form2's fields and then submitting this form instead.

解决方案

Your code should work across all browsers, but if you want to be absolutely sure you could do

$("#form1").submit(function(evt) {
    evt.preventDefault(); // cancel the default behavior
    $("#form2").submit();
    return false;
});

Using the .preventDefault() method ensures that you cancel the default behavior before doing something that might interfere with it..

这篇关于防止一个表单提交并提交另一个表单 - 此方法是否可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆