代码之家  ›  专栏  ›  技术社区  ›  Yuval Karmi

如何找出我刚才在jQuery中提交的表单?

  •  2
  • Yuval Karmi  · 技术社区  · 14 年前

    $.post 函数以提交ajax请求:

    $('.typeAform').submit(function(){
        $.post('/home', { somevar : 'somevalue' }, function(){
             //do something with the original form
        });
        return false;
    });
    

    我想在提交表格后确认我的身份 $邮政 回调,以便我可以用它做一些事情(例如,改变它的背景色,删除它,等等…)。

    是否有一种方法可以标识我刚刚提交的表单而不使用全局变量(即以某种方式将其传递给回调)。

    谢谢!

    1 回复  |  直到 14 年前
        1
  •  3
  •   user113716    14 年前

    编辑:

    因为 submit 事件应该始终是窗体本身,也可以使用 target 财产 event 对象,如: e.target

    $('.typeAform').submit(function( e ){
        $.post('http://apple.com', { somevar : 'somevalue' }, function(){
             // e.target references the form that was submitted.
             alert(e.target)
        });
        return false;
    });​
    

    如果这给您带来了麻烦,那么如果您不想创建变量,还有其他方法可以避免创建变量。


    .submit() :

    var id = this.id;
    

    所以应该是:

    $('.typeAform').submit(function(){
        var id = this.id;
        $.post('/home', { somevar : 'somevalue' }, function(){
             //do something with the original form
             // Use the "id" here
        });
        return false;
    });
    

    或者如果你想要表单本身,只需要引用 this .

    $('.typeAform').submit(function(){
        var theForm = this;
        $.post('/home', { somevar : 'somevalue' }, function(){
             //do something with the original form
             // Use the "theForm" here
             alert( theForm.id );
             $(theForm).someJQueryMethod()
        });
        return false;
    });
    

    $.post 不再引用 <form> . 这就是为什么我们在变量中引用它。