我为折扣制作了一个小的jQuery插件,如果我不使用回调函数,我会在折扣后发现错误:" TypeError:回调未定义"
CODE:
$.fn.countdown = function (options,callback) {
var settings=$.extend({
duration : 0,
interval : 1000,
text_before : "",
text_after : "",
disable : false,
}, options );
var callback,
container = $(this[0]).html(settings.text_before + settings.duration + settings.text_after),
countdown = setInterval(function (){
var dd = --settings.duration;
if(settings.disable==true){
clearInterval(countdown);
}
else if (dd > 0){
container.html(settings.text_before + dd + settings.text_after);
} else {
clearInterval(countdown);
callback.call(container);
};
}, settings.interval);
};
示例1 - 使用回调功能:
$("#timer").countdown({
duration : 3, // Discount start from defined number (in this case 3 seconds) DEFAULT: 0
text_before : "Redirection begins in exactly ", // initial text before number (example: Redirection begins in exactly 3), DEFAULT: blank
text_after : " seconds" // initial text after number (example: 3 seconds), DEFAULT: blank
},
// callback function when discount stop on 0
function(){
this.html("Done counting, redirecting.");
window.location = "http://www.creativform.com";
});
示例2 - 没有回调函数:
$("#timer").countdown({
duration : 3, // Discount start from defined number (in this case 3 seconds) DEFAULT: 0
text_before : "Redirection begins in exactly ", // initial text before number (example: Redirection begins in exactly 3), DEFAULT: blank
text_after : " seconds" // initial text after number (example: 3 seconds), DEFAULT: blank
});
任何帮助?
答案 0 :(得分:3)
试试这个
$.fn.countdown = function (options,callback) {
var settings=$.extend({
duration : 0,
interval : 1000,
text_before : "",
text_after : "",
disable : false,
}, options );
var
container = $(this[0]).html(settings.text_before + settings.duration + settings.text_after),
countdown = setInterval(function (){
var dd = --settings.duration;
if(settings.disable==true){
clearInterval(countdown);
}
else if (dd > 0){
container.html(settings.text_before + dd + settings.text_after);
} else {
clearInterval(countdown);
if (typeof callback === 'function') {
callback.call(container);
}
};
}, settings.interval);
};