[英]Button doesn't show after document.write
I made a rock, paper, scissors game and in the program, I have a button that should come up but it never does, It keeps giving me an error that says, "Uncaught TypeError: Cannot read property 'style' of null".我做了一个石头剪刀布游戏,在程序中,我有一个按钮应该出现但它从来没有出现,它一直给我一个错误,说“未捕获的类型错误:无法读取 null 的属性‘样式’”。 And if I get rid of the last "if" statement, it shows up but then disappears after it is clicked once.
如果我去掉最后一个“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>
The document.write
will overwrite your entire DOM, so the button you initialized onload will actually be overwritten by the contents of your document.write
. document.write
会覆盖你的整个 DOM,所以你在 onload 初始化的按钮实际上会被你的document.write
的内容覆盖。
However, if you do not want your content to disappear, I suggest making a new div
and using document.getElementById("div_id").innerHTML
in place of your document.write()
commands in order to save the button.但是,如果您不希望您的内容消失,我建议创建一个新的
div
并使用document.getElementById("div_id").innerHTML
代替您的document.write()
命令以保存按钮。
When you use document.write
, it will display its content by overwriting all the DOM elements.当您使用
document.write
,它将通过覆盖所有 DOM 元素来显示其内容。
So you need to use innerHtml
for displaying the contents keeping your DOM Alive.因此,您需要使用
innerHtml
来显示使 DOM 保持活动状态的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.