我在创建回调函数时遇到问题。首先,据我所知,回调就像一个参数,当它的“父”函数中的所有动作都完成时触发。例如:
$('p').hide('slow', function() {
$(this).show('slow');
});
首先隐藏<p>
,然后再次显示。
如何在随机插件中应用此类回调?
例如,插件看起来像这样:
$.fn.myPlugin = function(settings) {
return this.each(function() {
settings = $.extend({ onShow: null }, settings);
$(this).hide('slow'); /*This action should happen first (First action)*/
if ( $.isFunction( settings.onShow ) )
settings.onShow.call(this);/*Callback should fire after First action has stopped*/
}
});
};
$(document).ready(function()
$('p').myPlugin({
onShow: function() {
alert('My callback!');/*Both actions(element hiding and alert )
fire simultaneously, but I need alert
to fire after element is hidden*/
}
});
});
答案 0 :(得分:4)
您无法在随机插件中应用它。如果在不同事件发生时没有编写插件来触发回调函数,则无法使用它们。
答案 1 :(得分:1)
callback function
是一个函数,它被传递给另一个函数/方法并在某个时刻被调用。
如果我们创建一个像
这样的函数function mightyplugin(foo, callback){
// big code block here
callback.apply(this, [foo]);
}
我们现在有一个函数,它调用另一个函数。在此示例中,它通过它解析one
参数,并在this
范围内调用我们的回调函数。
通话看起来像
mightyplugin("Bar!", function(param){
alert(param);
});
我们将一个匿名函数(更精确地,一个引用)传递给mightyplugin()
,我们可以在那里访问我们的参数,因为我们称这个匿名函数有一个范围和一个参数数组(只保存原始参数)这里的参数)。
这些构造必须已经由插件实现,否则您需要创建自己的功能。
答案 2 :(得分:0)
function loadAjax(paramUrl, paramData, paramType, paramAsync) {
var result = ""
$.ajax({
url: paramUrl,
data: paramData,
type: paramType,
async: paramAsync,
success: function (res) {
result = res
},
error: function (data) {
alert("Unexpected error: " + data.val());
}
});
return result;
}