2015-11-02 139 views
1

我正在处理一个计时器代码,并且面临与它有关的问题,并且posted a question与此有关。经过讨论,感谢@James,我发现这是JSFiddle问题。onclick函数不能在JSFiddle上工作,但在CodePen上工作

的jsfiddle链接http://jsfiddle.net/RajeshDixit/0gvfc5yy/4/

CodePen链接http://codepen.io/rajesh_dixit/pen/RWBowQ

当你的jsfiddle运行它,你会得到以下错误

Uncaught ReferenceError: startTimer is not defined

但工程罚款CodePen和下面的代码段。

function timer() { 
 
    var time = { 
 
     sec: 00, 
 
     min: 00, 
 
     hr: 00 
 
    } 
 
    var max = 59; 
 
    var interval = null; 
 

 
    function update(str) { 
 
     time[str]++; 
 
     time[str] = time[str] % 60; 
 
     if (time[str] == 0) { 
 
      str == "sec" ? update("min") : update("hr"); 
 
     } 
 
     print(str); 
 
    } 
 

 
    function print(str) { 
 
     var _time = time[str].toString().length == 1 ? "0" + time[str] : time[str]; 
 
     document.getElementById("lbl" + str).innerHTML = _time; 
 
    } 
 

 
    function initInterval() { 
 
     interval = setInterval(function() { 
 
      update("sec"); 
 
     }, 1000); 
 
    } 
 

 
    function stopTimer() { 
 
     clearInterval(interval); 
 
    } 
 

 
    return { 
 
     'init': initInterval, 
 
      'stop': stopTimer 
 
    } 
 
}; 
 

 
var time = new timer(); 
 

 
function startTimer() { 
 
    time.init(); 
 
} 
 

 
function endTimer() { 
 
    time.stop(); 
 
}
<div> <span id="lblhr">00</span> 
 
: <span id="lblmin">00</span> 
 
: <span id="lblsec">00</span> 
 

 
</div> 
 
<button onclick="startTimer()">Start</button> 
 
<button onclick="endTimer()">Stop</button>

回答

1

在的jsfiddle中,装载JS选项可以被配置。将其从onload更改为in <head>标记。它的工作原理,检查this更新一个。

请点击这里JSFiddle documentation了解更多信息。

+0

是的,这是问题。谢谢。 – Rajesh

相关问题