你必须读取Javascript函数/变量作用域 。 您的start
函数在first
函数中定义,因此它被视为该函数的本地函数。 为了使其在脚本中的任何位置可用/可调用,它必须属于全局或窗口对象的浏览器。 有几种方法可以实现这一目标。
1)在第一个函数之外定义start
变量作为窗口对象的属性。 然后,在第一个函数内部,为它分配一个函数引用。
var start = null; //defined variable outside of any function, and so has global scope
function first()
{
alert("First")
//assign a function to global variable `start`
start = function()
{
alert("start");
}
}
first(); //when you invoke first, it creates the inner function and assigns its reference to the global `start` variable, which can then be invoked
start();
2)使用闭包,从外部函数返回一个命名函数:
function first()
{
alert("First");
var start = function()
{
alert("start");
}
return start;
}
3)上面略有变化,从外部函数返回一个匿名函数:
function first()
{
alert("First");
return function()
{
alert("start");
}
}
在上面的(2)和(3)中,当您第一次调用该函数时,它将发出警报First
,然后它将返回一个您可以立即执行的函数或者为变量执行分配一个变量。 例如:
first()(); //alerts `First`, which returns a function reference, which reference is executed right away, to the alert `start`
//alerts `First`, then assigns returned function to the variable `start`
var start = first(); //`start` now holds a function reference which you can execute anytime, like so:
start(); //alerts `start`
最后,作为一个快速提醒,强烈建议您使用事件侦听器将事件分配给元素,而不是直接在元素中使用onclick
或onwhatever
属性。 这也符合关注点分离的原则 。
接下来,更新的代码应如下所示:
HTML
<input id="start" value="start" type="button"><!-- notice no `onclick` attribute attached to it -->
使用Javascript将click事件监听器附加到按钮:
var startBtn = document.getElementById("start");
if (typeof startBtn.addEventListener === "function")
{
startBtn.addEventListener("click", function(){first()()}, false);
}
else if (typeof startBtn.attachEvent === "function")
{
startBtn.attachEvent("onclick", function(){first()()});
}
else
{
startBtn.onclick = function(){first()()}
}