Jquery倒计时计时器与到期回调
jquery count down timer with expiry callback?
我正在使用keith-wood插件来生成一个计数计时器。
它工作得很好,但当使用回调选项我有问题
$(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'
});
})
onExpiry: function() {
timerdone('welcome');
},
不调用您的函数,而是使用匿名函数将其作为引用传递。
展开@Brad M的回答——
你在JS中犯了一个相对常见的错误——不是传递一个函数的引用,而是调用它并传递它的返回值。
如
// 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
});
相关文章:
- AngularJS:我可以跳过函数参数回调吗
- 要求未定义JS回调参数
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- 自引用回调
- 测试Angular Service解决错误回调中的promise
- 如何将一个JavaScript函数回调为多个函数
- JavaScript回调函数
- 用于回调的javascript参数
- 将json回调数据转换为日期
- 承诺在非节点式回调上使用Bluebird
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- 如何使用jqueryAJAX从页面中回调多个变量
- jquery Onclick函数带有导致双击的回调排序函数
- Javascript点击事件回调不起作用
- 一旦加载并渲染了角度引导typeahead,就使用回调
- 成功回调永远不会被JSONP请求调用
- 如何让程序员在javascript中实现正确的回调
- Jquery倒计时计时器与到期回调