以下脚本在IE6、IE7、IE8 Beta2、Firefox 3、Chrome等浏览器中测试通过。
Javascript 脚本:
Code
// This function is used for firing the event in IE & Nescape.
function FireEvent(controlID, eventName)
{
if (document.all) // For IE.
{
eval("document.getElementById(\"" + controlID + "\")." + eventName + "();");
}
else // For Nescape
{
var e = document.createEvent('HTMLEvents');
e.initEvent(eventName, false, false);
document.getElementById(controlID).dispatchEvent(e);
}
}
HTML测试脚本:
Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script type="text/javascript">
function DoClick()
{
FireEvent("button2", "click");
}
function Display(control)
{
alert(control.value);
}
function FireEvent(controlID, eventName)
{
if (document.all) // For IE.
{
eval("document.getElementById(\"" + controlID + "\")." + eventName + "();");
}
else // For Nescape
{
var e = document.createEvent('HTMLEvents');
e.initEvent(eventName, false, false);
document.getElementById(controlID).dispatchEvent(e);
}
}
</script>
</HEAD>
<BODY>
<input id="button1" type="button" value="I'm Button1." onclick="DoClick();" />
<input id="button2" type="button" value="I'm Button2." onclick="Display(this);" />
</BODY>
</HTML>