1

我做了一个石头、纸、剪刀和代码末尾的按钮的游戏,单击一次后,它就消失了,一次又一次地重复该代码是没有意义的。

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!!!!");
    }
    else if(userChoice=="paper" && computerChoice=="rock"){
        document.write('<span style="color:red">You win!</span>');
    }
    else if(userChoice=="rock" && computerChoice=="scissors"){
        document.write('<span style="color:red">You win!</span>');
    }
    else if(userChoice=="scissors" && computerChoice=="paper"){
        document.write('<span style="color:red">You win!</span>');
    }
    else if(userChoice=="scissors" && computerChoice=="rock"){
        document.write('Sorry, you lose.');
    }
    else if(userChoice=="rock" && computerChoice=="paper"){
        document.write("Sorry, you lose.");
    }
    else if(userChoice=="paper" && computerChoice=="scissors"){
        document.write("Sorry, you lose.");
    }
    else if(userChoice=="Chuck Norris"){
        document.write("This program bows down to your superiority, YOU WIN!!!!");
    }
    document.write('<button type="button" style="display:block;"  onclick="game()">Play Again!</button>');

}
<body onload="game()">

4

2 回答 2

2

将代码写入如下元素或类似内容。Document.write 往往会使东西消失。

<h1 id='myText'></h1>

document.getElementById('myText').innerHTML = '我写给文档的内容'

于 2013-06-20T03:04:03.193 回答
2

忘掉document.write吧。使用 div 将内容写入。

<div id="mydiv"></div>

并像这样写给div:

document.getElementById("mydiv").innerHTML += "Sorry, you lose";

当然你可以将“mydiv”放入一个变量中并重用它。

var mydiv = document.getElementById("mydiv");
mydiv.innerHTML += "Sorry, you lose";
mydiv.innerHTML += "Sorry again";
于 2013-06-20T03:11:02.057 回答