JS代码在jsbin中运行而不在jsfiddle或Chrome / Safari中运行?

时间:2015-04-02 02:45:18

标签: javascript debugging jsbin

我试图弄清楚为什么这段代码只能在jsbin中工作,而不是在jsfiddle或任何网页浏览器中作为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";
}

1 个答案:

答案 0 :(得分:0)

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

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

当您尝试从on<event> =“”属性调用它们时,您尝试在全局范围内访问它们,这会在控制台中出现Uncaught ReferenceError: startClock is not defined这样的错误。

Frameworks & Extensions下左侧面板中的第二个下拉菜单更改为小提琴左侧面板中的body / head,以添加没有包装函数的脚本

演示:Fiddle