setInterval() 传递参数给 alertFunc 函数 ( IE9 及其更早版本不支持):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>雅爱笔记_www.5devip.com</title> </head> <body> <p>点击按钮每 2 秒输出 "Hello"。</p> <p>实例中,我们也会输出传递给 alertFunc() 函数的参数 ( IE9 及更早版本不支持 )。</p> <button onclick="myStartFunction()">开始</button> <button onclick="myStopFunction()">停止</button> <p id="demo"></p> <p id="demo2" style="color:red;"></p> <script> var myVar; function myStartFunction() { myVar = setInterval(alertFunc, 2000, "Runoob", "Google"); } function alertFunc(param1, param2) { document.getElementById("demo").innerHTML += "Hello "; document.getElementById("demo2").innerHTML = "传递给 alertFunc() 的参数: <br>" + param1 + "<br>" + param2 + "<br>"; } function myStopFunction() { clearInterval(myVar); } </script> </body> </html>
setInterval() 使用匿名函数,则所有浏览器都支持
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>雅爱笔记_www.5devip.com</title> </head> <body> <p>点击按钮每 2 秒输出 "Hello"。</p> <p>实例中,我们也会输出传递给 alertFunc() 函数的参数 ( 兼容所有浏览器 )。</p> <button onclick="myStartFunction()">开始</button> <button onclick="myStopFunction()">停止</button> <p id="demo"></p> <p id="demo2" style="color:red;"></p> <script> var myVar; function myStartFunction() { myVar = setInterval(function(){ alertFunc("Runoob", "Google"); }, 2000); } function alertFunc(param1, param2) { document.getElementById("demo").innerHTML += "Hello "; document.getElementById("demo2").innerHTML = "传递给 alertFunc() 的参数: <br>" + param1 + "<br>" + param2 + "<br>"; } function myStopFunction() { clearInterval(myVar); } </script> </body> </html>