簡體   English   中英

jquery.form.js-如何在提交時獲取當前表單?

[英]jquery.form.js - How to get current form on submit?

我有這個標記

<form action="..." id="form1" class="foo">...</form>
<form action="..." id="form2" class="foo">...</form>
...

我有這個JavaScript代碼

$('.foo').ajaxForm({
    dataType: 'json',
    success: function (data) {
       // TODO: How do I get the form that triggered this?
       console.log( $(this) );
    }
});

正如您在Javascript代碼中看到的那樣,我想在提交並成功后獲取當前的form元素。 輸出$(this)並沒有顯示任何指向當前form元素的內容。

如何獲取成功函數中的當前表單元素?

假設您正在使用jQuery Form Plugin

您可以使用第四個參數

 success: function (data, statusText, xhr,  form ) {

參考文獻

成功:提交表單后調用的回調函數。 如果提供了“成功”回調函數,則在從服務器返回響應后將調用它。 它傳遞了以下參數:

  1. responseText或responseXML值(取決於dataType選項的值)。
  2. statusText
  3. xhr(如果使用jQuery <1.4,則為jQuery包裹的表單元素)
  4. jQuery包裝的表單元素(如果使用jQuery <1.4,則為未定義)

采用 :

context通過this轉化為成功的功能

檢查以下鏈接:重復

$ .ajax上下文選項

如何將對象上下文傳遞給jQuery.ajax JSONP回調?

使用beforeSubmit回調:

beforeSubmit: function(arr, $form, options){
    options.context = $form;
}

這里$form是這是越來越Ajax化的當前表單,您可以在上下文到options的電流ajaxFormoptions.context = $form; 因此,現在它將保存正在提交的當前表單,您可以獲取當前上下文。


像這樣的東西:

$('.foo').ajaxForm({
   dataType: 'json',
   beforeSubmit: function(arr, $form, options){
    options.context = $form;
   },
   success: function (data) {
     // TODO: How do I get the form that triggered this?
     console.log( $(this) );
   }
});

您可以將代碼更改為此:

var fooForm = $('.foo');
fooForm.ajaxForm({
    dataType: 'json',
    success: function (data) {
       // TODO: How do I get t

       console.log( fooForm);
    }
});

您無法獲得$(this),因為在成功的回調函數中,“ this”指向Windows。

實際上,您可以將代碼編寫為以下樣式:

var fooForm = $('.foo');
fooForm.ajaxForm({
    dataType: 'json',
    success: successCallback
});
function successCallback(data){
    //'this' point to window : ) 
    console.log( fooForm);

}

希望這會有所幫助。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM