[英]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 ) {
成功:提交表單后調用的回調函數。 如果提供了“成功”回調函數,則在從服務器返回響應后將調用它。 它傳遞了以下參數:
- responseText或responseXML值(取決於dataType選項的值)。
- statusText
- xhr(如果使用jQuery <1.4,則為jQuery包裹的表單元素)
- jQuery包裝的表單元素(如果使用jQuery <1.4,則為未定義)
使用beforeSubmit
回調:
beforeSubmit: function(arr, $form, options){
options.context = $form;
}
這里$form
是這是越來越Ajax化的當前表單,您可以在上下文到options
的電流ajaxForm
與options.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.