2012-10-25 50 views
-3
<!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> 

onclick函數在IE中不起作用,但在Chrome和Firefox中正常工作。我找不到這個錯誤。爲什麼一個正常的功能不起作用。函數加載內容,但點擊寫入事件處理程序的前兩個按鈕不會僅更改IE中的按鈕顏色。請幫助我...在此先感謝Javascript onclick函數不起作用

+0

你的問題可能是'ansArray [0]'變量的範圍。嘗試將其聲明爲腳本頂部的全局變量。 –

+0

@ GeekNum88不是這樣。他只在'abc()'函數內訪問'ansArray'。您可能會因格式不佳而感到困惑。 – Barmar

+0

我正在研究這個問題,我對它有點困惑。任何聲明的數組都被完全忽略。即即使是那些在該功能之外製造的。 – Rhyono

回答

0

這裏的問題是,使用document.write顯然會覆蓋JavaScript。如果您將document.write()切換爲document.body.innerHTML +=,則說明問題已解決。您的後兩個按鈕不適用於該代碼,因爲您專門撥打按鈕01,而後兩個按鈕則是34

+0

他說,「前兩個按鈕寫事件處理程序」。所以他不希望第二對有處理程序。 – Barmar

+0

@Barmar我沒有注意到,但我的回答仍然是對他的問題的正確評估和解決方案。 – Rhyono

+0

給一些想法讓按鈕使用document.body.innerHTML + = – user1767304