Javascript 带到期回调的jquery倒计时?
我正在使用插件生成计数计时器。Javascript 带到期回调的jquery倒计时?,javascript,jquery,Javascript,Jquery,我正在使用插件生成计数计时器。 它工作得很好,但是当使用回调选项时,我遇到了问题 $(document).ready(function(){ function timerdone(){ alert('welcome'); } $('#id').countdown({ until: +300,
它工作得很好,但是当使用回调选项时,我遇到了问题
$(document).ready(function(){
function timerdone(){
alert('welcome');
}
$('#id').countdown({
until: +300,
compact: true,
onExpiry: timerdone,
format: 'HMS'
});
})
对于上面的示例,它可以正常工作,但在加载变量后将变量传递给回调函数和页面调用函数时会出现问题
$(document).ready(function(){
function timerdone(msg){
alert(msg);
}
$('#id').countdown({
until: +300,
compact: true,
onExpiry: timerdone('welcome'),
format: 'HMS'
});
})
不要调用函数,而是使用匿名函数将其作为引用传递
不要调用函数,而是使用匿名函数将其作为引用传递。要展开@Brad M的答案-- 您在JS中犯了一个相对常见的错误——您不是向函数传递引用,而是调用函数并传递其返回值 乙二醇
//在下面的示例中,onExpiry需要一个函数引用
//(也称为函数句柄)。该函数将被调用
//后来。
...
onExpiry:TimerOne,
//这很好,您正在传递对函数的引用
onExpiry:timerdone(),
//很多人都会犯这个错误。它正在调用函数(使用
//无参数),然后发送函数的返回值
onExpiry:timerdone(‘欢迎’),
//这是你的错误。与上面一样,您将调用该函数
//按预期发送函数引用。你在调用
//函数有1个参数,但参数不是问题所在。问题
//您正在调用函数并发送其结果(返回
//价值)作为
//
//有不同的方法来修复它,@Brad的解决方案是一个很好的方法。
展开@Brad M的答案--
您在JS中犯了一个相对常见的错误——您不是向函数传递引用,而是调用函数并传递其返回值
乙二醇
//在下面的示例中,onExpiry需要一个函数引用
//(也称为函数句柄)。该函数将被调用
//后来。
...
onExpiry:TimerOne,
//这很好,您正在传递对函数的引用
onExpiry:timerdone(),
//很多人都会犯这个错误。它正在调用函数(使用
//无参数),然后发送函数的返回值
onExpiry:timerdone(‘欢迎’),
//这是你的错误。与上面一样,您将调用该函数
//按预期发送函数引用。你在调用
//函数有1个参数,但参数不是问题所在。问题
//您正在调用函数并发送其结果(返回
//价值)作为
//
//有不同的方法来修复它,@Brad的解决方案是一个很好的方法。
onExpiry: function() {
timerdone('welcome');
},
// in the following, onExpiry is expecting a function reference
// (also called a function handle). The function will be invoked
// later on.
...
onExpiry: timerdone,
// this worked fine, you were passing a reference to the function
onExpiry: timerdone(),
// this MISTAKE is something many people do. It is invoking the function (with
// no arguments) and then sending the function's return value for <onExpiry>
onExpiry: timerdone('welcome'),
// this was your MISTAKE. Same as above, you're invoking the function instead
// of sending the function reference as is expected. You're invoking
// the function with 1 argument, but the argument isn't the issue. The issue
// is that you're invoking the function and sending its result (return
// value) as <onExpiry>
//
// There are different ways to fix it, @Brad's solution is a good one.
var counter = $('#counter');
var due = new Date();
due.setHours(due.getHours()+24);
due.setSeconds(due.getSeconds() + 3);
var dueMinus24Hours = new Date(due);
dueMinus24Hours.setHours(due.getHours()-24);
var timeout = dueMinus24Hours-new Date();
setTimeout(function() {
counter.countdown('option', { format: 'HMS' });
}, timeout);
counter.countdown({
until: due,
format: 'OD',
padZeroes: true
});