我正在开发一个应用程序,它允许我单击网页上的按钮,然后启动我的计时器对象。但是,计时器不会启动onclick。
<script type="text/javascript">
var Timer = function()
{
// Property: Frequency of elapse event of the timer in millisecond
this.Interval = 1000;
// Property: Whether the timer is enable or not
this.Enable = new Boolean(false);
// Event: Timer tick
this.Tick;
// Member variable: Hold interval id of the timer
var timerId = 0;
// Member variable: Hold instance of this class
var thisObject;
// Function: Start the timer
this.Start = function()
{
this.Enable = new Boolean(true);
thisObject = this;
if (thisObject.Enable)
{
thisObject.timerId = setInterval(
function()
{
thisObject.Tick();
}, thisObject.Interval);
}
};
// Function: Stops the timer
this.Stop = function(){
thisObject.Enable = new Boolean(false);
clearInterval(thisObject.timerId);
};
};
//counts down the timer
function timer_tick()
{
index = index - 1;
document.getElementById("blue").innerHTML =index;
if (index === 0)
{
obj.Stop();
}
}
如果我删除函数startBlue()但将代码保留在其中,则计时器将在页面加载时运行。因此,在查看我的代码后,我认为问题出在我调用startBlue(在html下面)或者在这个函数中的某个地方。
function startBlue(){
var index = 300;
var obj = new Timer();
obj.Interval = 1000;
obj.Tick = timer_tick();
obj.Start();
}
</script>
<body>
<div id ="Objectives">
Your Objectives:
<br>
<br>
<label>Blue Buff:</label>
<button id="yosb" onclick ="startBlue();">Start Blue</button>
<h2 id = "blue">
</h2>
</div>
</html>
答案 0 :(得分:3)
您的问题不是空间,而是范围和参考问题。
var index, obj; //define index and obj outside of startBlue().
function startBlue(){
index = 300; //initialize without redefining (remove 'var').
obj = new Timer(); //initialize without redefining (remove 'var').
obj.Interval = 1000;
obj.Tick = timer_tick; // store the actual function in obj.Tick, not the return (remove the '()' from the end of timer_tick)
obj.Start();
}
如果在函数内部定义变量,则该变量只能在该函数的范围内访问。通过在外部定义它,允许从外部范围访问该变量。
要将函数存储在变量中,必须确保不要在函数名末尾包含parens。否则该函数将首先执行,然后返回值将存储在变量中而不是它自己的函数中。
答案 1 :(得分:0)
以下一行
<button id="yosb" onclick ="startBlue();">Start Blue</button>
应改为
<button id="yosb" onclick="startBlue();">Start Blue</button>
您在 onclick 和 = 之间添加了不必要的空格。