javascript - .innerHTML 不更新 Javascript 中的 HTML

标签 javascript

正在进行石头剪刀布作业,其中全局变量根据计算机还是人类获胜而向前递增。我的函数工作正常,但使用 .innerHTML 时记分板不会更新。有什么建议吗?

document.getElementById("humanScore").innerHTML = humanTotal;
document.getElementById("computerScore").innerHTML = compTotal;

http://codepen.io/anon/pen/GvpaJ

最佳答案

您遇到了一些问题。

在您的 play 函数中,您没有使用 computerChoice 变量执行任何操作,它应该是对 compPlay() 函数调用的结果。目前它是 var computerChoice = compPlay,它实际上是将 computerChoice 分配给一个函数,而不是它的结果。

其次在测试if语句中,您再次检查值compPlay,这是一个函数,我认为它应该是computerChoice

第三。 compPlay 的返回值是一个索引,它应该是 compOptions 数组中的索引值

更新了下面的代码

var humanTotal =0;                                          
var compTotal=0;                                    

document.getElementById("rock").onclick = setRock;
document.getElementById("paper").onclick = setPaper;
document.getElementById("scissors").onclick = setScissors;

function setRock(){
    play("rock")
}

function setPaper(){
    play("paper")
}

function setScissors(){
    play("scissors")
}    

function play(humanChoice) {    
    var computerChoice = compPlay(); //<-- Change Here

    //And all the following if statements to check the computer choice
    if (humanChoice == "rock"){
        if (computerChoice  =="rock"){
        } else if (computerChoice =="scissors"){
            humanTotal++; 
        } else if (computerChoice =="paper"){
            compTotal++;
        }
    }

    if (humanChoice == "paper"){
        if (computerChoice  =="paper"){
        } else if (computerChoice =="rock"){
            humanTotal++; 
        } else if (computerChoice =="scissors"){
        compTotal++;
        }
    }

    if (humanChoice == "scissors"){
        if (computerChoice  =="scissors"){
        } else if (computerChoice =="paper"){
            humanTotal++; 
        } else if (computerChoice =="rock"){
            compTotal++;
        }
    }

    document.getElementById("humanScore").innerHTML = humanTotal;
    document.getElementById("computerScore").innerHTML = compTotal;

}   


function compPlay (){
    var compOptions = ['rock', 'paper', 'scissors'];    
    var randomChoice = Math.floor(Math.random()*compOptions.length);
    return compOptions[randomChoice]; //<-- Change Here

}

它与innerHTML无关,工作正常,只是分数始终为零。原因是因为测试“石头”、“布”或“剪刀”的 if 语句都没有解析为 true,因为 ComputerChoice 从未匹配“石头”、“布”或“剪刀”,所以很抱歉,但这是你的功能。

关于javascript - .innerHTML 不更新 Javascript 中的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23257378/

相关文章:

javascript - 如何在外部 JS 脚本运行完成后运行函数

javascript - jQuery : Hide a parent based on child property

javascript - 使用 javascript html 实时预览文本区域输入

事件处理程序中的 JavaScript 调用

javascript - 使用函数设置变量

javascript - JavaScript 关键字 `with` 真的被弃用了吗?

javascript - 如何在 Web View 中隐藏 xml 元素后删除空格

javascript - 为什么 Mag Pagination 和 Mag Sort 不起作用

javascript - 使用 ajax 请求下载文件

javascript - 显示数据,在 knockout 中一次显示一个对象元素