0

我有以下功能:

<script>
    var count=900;
    var countM;
    var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

    function timer()
    {
        count=count-1;
        countM=Math.floor(count/60);
        if (count <= 0)
        {
            clearInterval(counter);
            return;
        }

        for(var i=0; i<10; i++)
        {
            document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs"; // watch for spelling
        }
    }
</script>

我这样显示它:

<span id="<?php echo "timer".$theCounter; ?>"></span>
$theCounter++;

问题在于我想给它一个参数,这将是count我不知道该怎么做。

4

3 回答 3

1

像这样?

var counter = window.setInterval(function() {
    timer('parameter');
}, 1000);

我看不出 javascript 和 PHP 部分之间有什么关系。

于 2013-06-07T23:56:58.803 回答
1

'我想给它一个参数,这将是“计数”'

类似于以下内容:

function createTimer(count) {
    var countM,
        counter=setInterval(timer, 1000);

    function timer()
    {
        count -= 1;
        countM = Math.floor(count/60);
        if (count <= 0) {
            clearInterval(counter);
            return;
        }
        for(var i=0; i<10; i++) {
            document.getElementById("timer"+i).innerHTML=countM+"mins. "+(count%60)+ " secs"; 
        }
    }
}

...将为您提供一个函数,createTimer()您可以使用计数参数调用该函数:

createTimer(900);

如果你说你希望不同的跨度有不同的计数器,那么你可以这样做:

function createTimer(count, elementID) {
   // code exactly the same as above function except
   // remove the `for` loop and just reference the elementID
   // passed into the function:
   document.getElementById(elementID).innerHTML=countM+"mins. "+(count%60)+ " secs"; 
}

createTimer(900, 'timer1');
createTimer(200, 'timer2');
// etc.

演示:http: //jsfiddle.net/dUTk3/1/

于 2013-06-07T23:46:25.187 回答
0

Use the bind function prototype to create a function with default parameters.

timer.bind(null,count-1);

The first argument is function context (null means global), optional following parameters is set tho function arguments from left. The result is new function. So in your code:

function timer(count) {
    console.log(count); // do some stuff
    if(count>0) setTimeout(timer.bind(null,count-1),1000);
}

timer(10); // counts from 10 to 0 in 1s interval

See the fiddle

于 2013-06-08T00:17:06.227 回答