步骤/方法
当用鼠标单击页面的标签时,onClick 事件会被触发。该事件可以调用相应的函数,作为其事件处理函数。在函数中,可以是任意合法的JavaScript代码。
setTimeout 方法在执行时是在载入后延迟指定时间后,去执行一次表达式,仅执行一次。
alert 方法有一个参数,即希望对用户显示的文本字符串,该字符串不是 HTML 格式。该消息框提供了一个“确定”按钮让用户关闭该消息框,并且该消息框是模式对话框,也就是说,用户必须先关闭该消息框然后才能继续进行操作。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>使用匿名函数为定时器传递参数</title> <script language="javascript"> var userName = 'jack'; //根据用户名显示欢迎信息 function hello(_name) { alert('hello, ' + _name); } function _hello(_name) //创建一个函数,用于返回一个无参数函数 { return function() { hello(_name); } } function foo() //函数:直接调用 { window.setTimeout(hello(userName), 3000); //直接调用hello函数 } function bar() //函数:间接调用 { window.setTimeout(_hello(userName), 3000); //使用匿名函数为定时器传递参数 } </script> </head> <body> <center> <h1>使用匿名函数为定时器传递参数</h1> <hr> <br> <h5>单击相应按钮...</h5> <form name="form1" method="post" action=""> <label> <input type="button" onClick="foo()" name="button" id="button" value="hello"> </label> <label> <input type="button" onClick="bar()" name="button2" id="button2" value="_hello"> </label> </form> </center> </body> </html>
运行该程序后,页面中出现一组按钮,单击第一个按钮时立即弹出相应的消息框,如下图所示。单击“OK”按钮关闭消息框后单击第二个按钮,三秒钟后才弹出相应的消息框,如下图所示。