将倒数计时器的代码从javascript切换到jquery

时间:2013-06-24 22:21:19

标签: javascript jquery

我正在尝试将倒数计时器的这些代码从javascript切换到jquery所以我可以在同一页面中包含多个不同div ID的倒数计时器。

我对javascript或jquery不太满意,我发誓我浪费了超过15个小时!!

这是主页面代码

<script language="JavaScript">
TargetDate = "06/25/2013 5:00 AM";
CurrentDate = "<?= strftime('%c') ?>";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "It is finally here!";
</script>
<script src="js/countdown.js" type="text/javascript"></script>

countdown.js文件

function calcage(secs, num1, num2) {
  s = ((Math.floor(secs/num1))%num2).toString();
  if (LeadingZero && s.length < 2)
    s = "0" + s;
  return "<b>" + s + "</b>";
}

function CountBack(secs) {
  if (secs < 0) {
    document.getElementById("cntdwn").innerHTML = FinishMessage;
    return;
  }
  DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
  DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
  DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
  DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

  document.getElementById("cntdwn").innerHTML = DisplayStr;
  if (CountActive)
    setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}

function putspan() {
 document.write("<span id='cntdwn'></span>");
}


if (typeof(CountActive)=="undefined")
  CountActive = true;
if (typeof(FinishMessage)=="undefined")
  FinishMessage = "";
if (typeof(CountStepper)!="number")
  CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
  LeadingZero = true;


CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
  CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan();
var dthen = new Date(TargetDate);
var dnow = new Date(CurrentDate);
if(CountStepper>0)
  ddiff = new Date(dnow-dthen);
else
  ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

  

所以我可以在同一页面中包含不止1个倒数计时器,但不同的div ID。

因此,您必须创建函数的所有全局配置变量参数。并为id添加一个参数。

所以将整个脚本包装在

function makeCounter(DisplayId, TargetDate, CurrentDate, CountActive, CountStepper, LeadingZero, DisplayFormat, FinishMessage) {
    …
}

然后将使用

调用(在加载脚本之后,必须更改其顺序)
makeCounter("cntdwn",
            "06/25/2013 5:00 AM",
            "<?= strftime('%c') ?>",
            true, -1, true,
            "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.",
            "It is finally here!");

然后用cntdwn变量替换每个字符串DisplayId

这是基础,你的脚本应该工作,但它需要另外两个错误修正:

  • 合理使用局部变量,使用var statement声明它们。我发现sDisplayStrddiffgsecs未声明,但我可能错过了其他人。
  • 不推荐使用to-be - eval ed-string调用setTimeout,并且仅在CountBack位于全局范围内时才起作用,这不是任何更多。相反,传递一个函数:

    setTimeout(function() {
        CountBack(secs+CountStepper);
    }, SetTimeOutPeriod);
    

现在它会起作用。为方便起见,您也可以小写变量和函数名称,因为它们不是构造函数,但没有必要。