問題是與對象的變量:對象的全局變量
this.timer
它不是「全球性」,所以當我點擊停止按鈕變量的值是錯誤的。
如果我聲明一個全局變量MyObject(loke var mytimer;)並使用它來替代this.timer,它就可以工作。
這是我的代碼:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript" language="JavaScript">
var MyObject = {
init: function(){
this.timer = 0;
document.getElementById("btn1").onclick = function(){
MyObject.RunIt();
};
document.getElementById("btn2").onclick = function(){
clearInterval(this.timer);
};
},
RunIt: function(){
var x=0;
this.timer = setInterval(function(){
x++;
document.getElementById("spn").innerHTML=x;
}, 1000);
}
};
</script>
<style type="text/css">
</style>
</head>
<body onload="MyObject.init();">
<input type="button" id="btn1" value="Run"/>
<input type="button" id="btn2" value="Stop"/>
<span id="spn"></span>
</body>
</html>
「當我這樣做是錯誤的方式,它不工作」?我不明白你在問什麼...... – 2010-02-13 12:44:17
你在引用我嗎? – mariki 2010-02-13 12:47:33
我問,爲什麼我沒有得到this.timer的真正價值,當我點擊停止按鈕。 – mariki 2010-02-13 12:48:30