2011-11-29 60 views
2

真的很奇怪的事情正在發生,它在我document.write()以外window.onload = function(){}但是它不起作用,當我從裏面調用它。請注意,表格已創建(我可以看出,因爲我看到源代碼)。爲什麼我的表格在寫入'onload'時不顯示?

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<title>title</title> 
<style type="text/css"> 
#chessboard{margin:0;padding:0;border:2px solid #000} 
#chessboard td{margin:0;padding:0;height:44px;width:42px;border:1px solid #000;background-repeat:no-repeat} 
#chessboard td.ws{background-color:#ddd} 
#chessboard td.bs{background-color:#999} 
#chessboard td.bp{background-image:url('./pieces/bp.png')} 
#chessboard td.br{background-image:url('./pieces/br.png')} 
#chessboard td.bn{background-image:url('./pieces/bn.png')} 
#chessboard td.bb{background-image:url('./pieces/bb.png')} 
#chessboard td.bq{background-image:url('./pieces/bq.png')} 
#chessboard td.bk{background-image:url('./pieces/bk.png')} 
#chessboard td.wp{background-image:url('./pieces/wp.png')} 
#chessboard td.wr{background-image:url('./pieces/wr.png')} 
#chessboard td.wn{background-image:url('./pieces/wn.png')} 
#chessboard td.wb{background-image:url('./pieces/wb.png')} 
#chessboard td.wq{background-image:url('./pieces/wq.png')} 
#chessboard td.wk{background-image:url('./pieces/wk.png')} 

</style> 
<script type="text/javascript"> 
var map="",i,ii,wsbs=true; 
var abc=["a","b","c","d","e","f","g","h"]; 

map+="<div align=\"center\"><table id=\"chessboard\" cellpadding=\"0\" cellspacing=\"0\"><tbody>"; 
for(i=8;i>0;i--){ 
map+="<tr>"; 
for(ii=0;ii<8;ii++){ 
map+="<td id=\""+abc[ii]+""+i+"\" class=\""; 
if(wsbs==true)map+="ws";else map+="bs"; 
map+="\">&nbsp;</td>"; 
if(ii!=7)wsbs=!wsbs; 
} 
map+="</tr>"; 
} 
map+="</tbody></table></div>"; 

//document.write(map); works here 

window.onload = function(){ 
document.write(map); 
} 

</script> 
</head> 
<body> 
</body> 
</html> 

回答

4

當你調用document.write()在頁面加載後(通過window.onload()),您可以有效地抹殺頁面,因爲它已經呈現。相反,您應該將頁面上某個現有元素的innerHTML設置爲map的內容。由於您有一個空的<body>,因此寫入機構的innerHTML將是安全的。否則,我會建議在<body>內部創建一個佔位符<div>,並修改它的innerHTML

window.onload = function(){ 
    document.body.innerHTML = map; 
} 
+0

爲什麼你在括號內附上'map'? – ajax333221

+0

@ ogps92這是一個複製/粘貼錯誤,已經更正。 –

1

你正在寫你的表<head>,所以你的瀏覽器不會解釋它。你需要在身體中有這樣的:

<script> 
document.write(map); 
</script> 
相關問題