jquery倒计时器具有到期回调?

时间:2013-04-15 20:50:45

标签: javascript jquery

使用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'
                                 });  
                    })

3 个答案:

答案 0 :(得分:2)

onExpiry: function() {
    timerdone('welcome');
},

不使用调用函数,而是使用匿名函数将其作为引用传递。

答案 1 :(得分:1)

扩展@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.

答案 2 :(得分:0)

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
    });