简体   繁体   中英

Code works in chrome and firefox but fails in IE9

<!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>

This code segment is to change the colour of the two buttons on click event,works fine in chrome and firefox but the onclick functions does not work in IE9. Please help... Thanks in advance

Try calling the function like

(function abc(){
    // code here
})();

Also use ; after each function expression, ie myButton[0].onclick = function() {...}; .

Working here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM