Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

internet explorer - Javascript onclick functions do not work

<!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 setFont() {
   var i;
   for ( i = 0; i < document.all.length; i++) {
      document.all[i].style.fontFamily = "Verdana";
      document.all[i].style.fontSize = "16";
      document.all[i].style.color="black";
   }
};


function abc(a) {
    alert(a);
    ansArray = ['a'];
    for (i = 1; i <= a; i++) {
        document.write('<input type = "button" value = "a">');
        document.write('<input type = "button" value = "b">');
    }
    var myButton = document.getElementsByTagName("input");
    //alert(myButton.length);
    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";
    };
};?

setFont();
</script>
</head>

<body onload="Javascript:abc(2)">
hello
</body>
</html>

The onclick functions do not work in IE but work fine in chrome and firefox. I could not find the mistake. Why a normal function does not work. function loads the contents but onclicking the first two buttons for which event handelers are writen does not change the button colour in IE only. Please help me... Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem here is that using document.write apparently overwrites JavaScript as well. If you switch your document.write() to document.body.innerHTML += your problem is solved. Your latter two buttons won't work with that code because you are calling button 0 and 1 exclusively, while those second two are 3 and 4.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...