【问题标题】:How to know the form from a submit如何从提交中知道表单
【发布时间】:2014-11-12 16:48:59
【问题描述】:

我在一个页面中有几个表单,每个表单都有一个提交。但这不起作用,因为这将两种形式返回给我。有人知道这样做吗?

谢谢

$(".submit").click(function() {
    processBeforeSend($(".submit").closest("form"));
});


 function processBeforeSend(form) {

form.each($('input'), function() {

    if ($(this).attr('class') == 'integer'){
        validateInteger(field);
    }
    else{
        if (filedClass == 'radio'){
            validateRadio(field);
        }
        else{

        }
    }
});

【问题讨论】:

  • 使用click而不是submit意味着键盘提交会绕过你的代码!

标签: jquery forms submit


【解决方案1】:

使用click而不是submit意味着键盘提交会绕过你的代码!始终使用 submit 事件代替表单。如果您使用submit 事件,您的this form :)

此外,如果验证失败,您的验证可能需要表单“不”提交。因此,将事件对象传递给您的验证并在任何验证失败时调用 e.preventDefault()

例如

$(".submit").submit(function(e) {
    processBeforeSend($(this), e);
});

function processBeforeSend(form, e) {
    // validation calls 
    if (somethingFails){
        e.preventDefault()
    }
});

【讨论】:

    【解决方案2】:

    我不会使用submit 按钮的点击事件,而是让submit 按钮完成它的工作——触发表单的submit 事件:

    $("form").on( 'submit', processBeforeSend );
    
    
    function processBeforeSend() {
    
        //'this' in here refers to the form whose submit event was triggered.
        $(this).find('input').each(function(i, field) {
            //'field' was not defined but in here it equals 'this' 
            //and refers to the current input element
    
            //An element can have more than one class so $(this).attr('class') is not the way to go.
            if( $(this).hasClass('integer') ){
                validateInteger(field);
            } else if( $(this).hasClass('radio') ) {
                 validateRadio(field);
            } else {
    
            }
        });
    }
    

    【讨论】:

    • sumbit?那是二进制数学吗:)
    【解决方案3】:

    您需要找到包含被点击的.submit 元素的form,为此您可以使用this 来引用点击处理程序中被点击的.submit 元素

    $(".submit").click(function() {
        processBeforeSend($(this).closest("form"));
    });
    

    【讨论】:

    • 注意:使用click而不是submit表示键盘提交会绕过该功能。
    猜你喜欢
    • 2011-08-16
    • 2013-04-09
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多