[英]Button doesn't show after document.write
我做了一個石頭剪刀布游戲,在程序中,我有一個按鈕應該出現但它從來沒有出現,它一直給我一個錯誤,說“未捕獲的類型錯誤:無法讀取 null 的屬性‘樣式’”。 如果我去掉最后一個“if”語句,它會出現,但在單擊一次后消失。
<html>
<head>
<title> Rock, paper, scissors game</title>
<script>
function game(){
var userChoice= prompt("Do you choose rock, paper, or scissors?");
document.write("You chose " + userChoice + ". <br/>")
var computerChoice= Math.random();
if(computerChoice<=0.33){
computerChoice="rock";
}
else if(computerChoice<=0.67){
computerChoice="paper";
}
else{
computerChoice="scissors";
}
document.write("The computer chose " + computerChoice + ". <br/>");
if(userChoice==computerChoice){
document.write("TIE!!!!");
}
if(userChoice=="paper" && computerChoice=="rock"){
document.write('<p style="color:red">You win!</p>');
}
if(userChoice=="rock" && computerChoice=="scissors"){
document.write('<p style="color:red">You win!</p>');
}
if(userChoice=="scissors" && computerChoice=="paper"){
document.write('<p style="color:red">You win!</p>');
}
if(userChoice=="scissors" && computerChoice=="rock"){
document.write('Sorry, you lose.');
}
if(userChoice=="rock" && computerChoice=="paper"){
document.write("Sorry, you lose.");
}
if(userChoice=="paper" && computerChoice=="scissors"){
document.write("Sorry, you lose.");
}
if(userChoice=="Chuck Norris"){
document.write("This program bows down to your superiority, YOU WIN!!!!");
}
if(document.getElementById("buttonclick").style.display == "none"){
document.getElementById("buttonclick").style.display = "block";
}
}
</script>
</head>
<body onload="game()">
<button type="button" style="display:none;" id="buttonclick" onclick="game()">Play Again!</button>
</body>
</html>
document.write
會覆蓋你的整個 DOM,所以你在 onload 初始化的按鈕實際上會被你的document.write
的內容覆蓋。
但是,如果您不希望您的內容消失,我建議創建一個新的div
並使用document.getElementById("div_id").innerHTML
代替您的document.write()
命令以保存按鈕。
當您使用document.write
,它將通過覆蓋所有 DOM 元素來顯示其內容。
因此,您需要使用innerHtml
來顯示使 DOM 保持活動狀態的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.