我希望仅在单击按钮时调用 alertMe 函数,但它会在页面加载时被调用(调用 setInterval 调用它)。但是,如果我去掉 pageLoad 函数,则 startButton 为空,我将无法对其执行任何操作。在此先感谢大家!
/when user clicks start, start the animation
window.onload = pageLoad;
function pageLoad() {
var startButton = document.getElementById("start");
startButton.onclick = setInterval(alertMe,200);
}
function alertMe() {
alert("hi");
}
最佳答案
function pageLoad() {
var startButton = document.getElementById("start");
startButton.onclick = alertMe;
}
function alertMe() {
setInterval(function(){
alert("hi");
},200);
}
将您的时间间隔移到 alertMe
函数中,并将其作为引用传递给 startButton.onclick
关于javascript - setInterval() 如何与 button.onclick 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606480/