[英]how to run function after another one completes
我在另一個完成后運行功能時遇到問題。 我在這篇文章中嘗試回調,但這不起作用在另一個函數完成后執行 jquery 函數,所以也許我做錯了什么或者我的情況更復雜。
所以我有提交表單時運行的功能
$("#search-form").submit(ajaxSubmit(addSearchfuntion)); // addSearchfuntion is callback
function ajaxSubmit(callback) {
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function(result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
callback();
return false;
};
在此之后,當我將新表單添加到我的頁面時,我想運行另一個函數來處理這個新表單。
function addSearchfuntion(){
$('.Amount').change(updateQuantity);
}
那么如何解決這個案子呢?
您需要使用匿名函數來綁定submit
事件處理程序。 到目前為止,您正在執行ajaxSubmit()
方法並綁定其返回值,即false
作為事件處理程序。
$("#search-form").submit(function(){
ajaxSubmit.bind(this)(addSearchfuntion);
});
而且,調用callback
的方法done()
的回調方法$.ajax()
$.ajax(settings).done(function(result) {
// Your existing code
....
....
// call the callback
callback();
});
您非常接近,您需要將回調調用放在異步方法中
function ajaxSubmit(callback) {
// this will be executed linear
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
// this will be executed async
$.ajax(settings).done(function(result) {
// anything in here must be handled async, hence put your callback here
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
// call the callback
callback();
});
// this will be executed linear and most likely before the async method
return false;
};
只需在ajaxSubmit
返回函數:
function ajaxSubmit(callback) {
return function(){
var $form = $(this);
var settings = {
data: $(this).serialize(),
url: $(this).attr("action"),
type: $(this).attr("method")
};
$.ajax(settings).done(function(result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
});
callback();
return false;
}
};
將您的callback
執行放在您的ajax(settings).done
部分。 它看起來像這樣:
$.ajax(settings).done(function(result) {
var $targetElement = $($form.data("ajax-target"));
var $newContent = $(result);
$($targetElement).replaceWith($newContent);
$newContent.effect("slide");
if (typeof callback === "function") {
callback();
}
});
您還應該在調用之前檢查以確保callback
存在,這是if (typeof callback)...
check 背后的想法。 有關更多信息,請參閱此答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.