[英]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.