JS代码在jsbin中有效,在jsfiddle或Chrome/Safari中无效

JS Code Works in jsbin and Not in jsfiddle or Chrome/Safari?

本文关键字:Chrome Safari 无效 代码 jsbin 有效 JS jsfiddle      更新时间:2023-09-26

我试图弄清楚为什么这段代码只能在jsbin中工作,而不能在jsfiddle或任何web浏览器中作为html/js文件工作。我试过调试,但找不到结论。

我犯了一个错误,直接在jsbin中而不是在文档中进行编码。任何意见都将不胜感激。

http://jsbin.com/tuduxedohe/7/edit
http://jsfiddle.net/2rs1x5pz/

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Timer</title>
  <script type="text/javascript" src="part2.js"></script>
</head>
<body>
<h1><div id="time">00:00:00</div></h1>
<div id="result"></div>
<button id="start" onclick ="startClock();" >Start</button>
<button id="stop" onclick="stopTimer();">Stop</button>
<button id="clear" onclick="resetTimer();">Reset</button>
</body>
</html>
var currentTime = document.getElementById('time');
var hundreths = 0;
var seconds = 0;
var minutes = 0;
var t;
function startClock() {
function add() {

    hundreths++;
    if (hundreths > 99) {
        hundreths = 0;
        seconds++;
        if (seconds > 59) {
            seconds = 0;
            minutes++;
        }
        if(minutes >= 10) {
            seconds= 0;
            minutes= 0;
            stopTimer();
        }
    }

if (hundreths > 9 && seconds < 9) {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + hundreths;
  }
else if ((seconds > 9 ) && (hundreths < 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if((seconds > 9) && (hundreths > 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + hundreths;
}
else if ((minutes > 9) && (seconds < 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
else {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
   timer();
}

function timer() {
    t = setTimeout(add, 1);
}
timer();
} // end function start clock
function stopTimer() {
    document.getElementById("result").innerHTML = "<p>" + ("Your time is: " + minutes + " minutes, " + seconds + " seconds, " + "and " + hundreths + " hundreths") + "</p>";
    clearTimeout(t);
}
function resetTimer() {
  hundreths = 0; 
  seconds = 0; 
  minutes = 0;   
  currentTime.innerHTML = "00:00:00";
}

这是因为默认情况下,脚本添加在jsfiddle中的onload处理程序中,因此您的方法只能在该闭包的范围内使用。所以它将是

window.onload=function(){
    //your script is here
}

当您试图从on<event>="属性调用它们时,您正试图在全局范围内访问它们,这将在控制台中出现类似Uncaught ReferenceError: startClock is not defined的错误。

Frameworks & Extensions下左侧面板中的第二个下拉列表更改为fiddle左侧面板中身体/头部,以添加不带包装功能的脚本

演示:Fiddle