0

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

3 回答 3

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

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

于 2013-04-15T20:53:46.393 回答
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.
于 2013-04-15T21:21:37.340 回答
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
    }); 
于 2015-10-12T11:04:23.760 回答