javascript - document.write 后按钮不显示

标签 javascript html css

我做了一个剪刀石头布游戏,在程序中,我有一个应该出现的按钮,但它从来没有出现,它一直给我一个错误,说“未捕获的类型错误:无法读取属性‘样式’无效的”。如果我去掉最后一个“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() 命令以保存按钮。

关于javascript - document.write 后按钮不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17184803/

相关文章:

html - Gridview 标题向左对齐,在 IE9 上不起作用,但在 chrome 上有效

html - 无法在 github 页面上发布我的 Bootstrap 页面

html - 具有两个并排内联 block 元素的类似表格的布局?

javascript - 每当我单击列表项时,如何打开和关闭类(class)?

javascript - vue v-model 和 proxy 第一集不调用

html - 引导宽度问题

javascript - 如何在 html5 中仅将 <base> 标记用于特定的 anchor 标记

javascript - 追加 div 元素,然后使用 JQUERY 从右到左设置动画

javascript - 调整窗口大小时更改元素宽度(以 px 为单位)

javascript - Angular 6 : ERROR TypeError: el. toLowerCase 不是函数