代码适用于chrome和firefox,但在IE9中失败

时间:2012-10-23 16:35:42

标签: javascript internet-explorer-9

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>



<script language="javascript" type="text/javascript">
function abc()
{
ansArray = ['a'];   
document.write('<input type = "button" value = "a">');
document.write('<input type = "button" value = "b">');
var myButton = document.getElementsByTagName("input");

myButton[0].onclick = function() {
    if(ansArray[0] == 'a')
        myButton[0].style.backgroundColor = "green";
    else
        myButton[0].style.backgroundColor = "red";
}

myButton[1].onclick = function() {
    if(ansArray[0] == 'b')
        myButton[1].style.backgroundColor = "green";
    else
        myButton[1].style.backgroundColor = "red";
}
}
</script>
</head>

<body onload="abc()">
</body>
</html>

此代码段用于更改click事件上两个按钮的颜色,在chrome和firefox中工作正常,但onclick功能在IE9中不起作用。请帮忙...提前致谢

1 个答案:

答案 0 :(得分:1)

尝试调用类似

的功能
(function abc(){
    // code here
})();

在每个函数表达式之后也使用;,即myButton[0].onclick = function() {...};

Working here