<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>匿名函数</title>
</head>
<body>
<p>单击"事件测试"按钮,通过匿名函数处理事件</p>
<form name="MyForm" id="MyForm">
<input type="button" name="MyButton" id="MyButton" value="事件测试">
</form>
<script language="JavaScript" type="text/javascript">
document.MyForm.MyButton.onclick=new Function()
{
window.alert("You have clicked me");
}
</script>
</body>
</html>这个网页打开后就直接弹出"You have clicked me",而当单击按钮时则无反应,看了半天也没有查出错误
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>匿名函数</title>
</head>
<body>
<p>单击"事件测试"按钮,通过匿名函数处理事件</p>
<form name="MyForm" id="MyForm">
<input type="button" name="MyButton" id="MyButton" value="事件测试">
</form>
<script language="JavaScript" type="text/javascript">
document.getElementById("MyButton").onclick=new Function()
{
window.alert("You have clicked me");
}
</script>
</body>
</html>
<form name="MyForm" id="MyForm">
<input type="button" name="MyButton" id="MyButton" onclick="check()" value="事件测试">
</form>
<script language="JavaScript" type="text/javascript">
function check(){
document.getElementById("MyButton").onclick=new Function()
{
window.alert("You have clicked me");
}
} </script>
<script language="JavaScript" type="text/javascript">
document.MyForm.MyButton.onclick=AA;
function AA()
{
window.alert("You have clicked me");
}
</script> 这段代码是可以正确运行,但是却不是匿名函数,如果需要写成匿名函数,how?
function(msg){ alert(msg); }("You have clicked me");
document.MyForm.MyButton.onclick=new Function('window.alert("You have clicked me");')
document.getElementById("MyButton").onclick = function()
{
alert("test");
}
{
window.alert("You have clicked me");
}