【问题标题】:Counter value is not increasing, value remains constant in javascript计数器值没有增加,值在 javascript 中保持不变
【发布时间】:2020-05-02 02:14:19
【问题描述】:

为什么我的变量 pc_scoremy_score 没有增加?输出为 0。 我从代码中省略了另外两个 eventListener 格式的函数,但它不应该影响结果。 . 我编辑了可运行代码的帖子。谢谢你。 感谢您查看我的问题。



<script>

    var options = ['rock','paper','scissors']
    let my_score = 0; 
    var pc_score = 0; 

    let computerChoice ;


    function computerSelection() {

         computerChoice = options[Math.floor(Math.random()*options.length)]
         return computerChoice;

    }


    var results = document.getElementById("result")
    document.getElementById("rock").addEventListener("click", ()=> {
        playerChoice=rock;
        computerSelection();
        if (computerChoice=='rock'){
             results.innerHTML="It is a tie";
        } else if (computerChoice=='paper'){
            results.innerHTML="It is a loss";
                 pc_score += 1;
        }else if (computerChoice=='scissors'){
            results.innerHTML="It is a win";
            my_score+= 1
        }

})

     const you = document.getElementById("You")
        you.innerHTML= my_score
    const computer = document.getElementById("Computer")
        computer.innerHTML=pc_score

  </script>

【问题讨论】:

  • computerChoice 未定义。请提供一个可运行的示例。
  • you.innerHTML= my_score 不会绑定 my_score 到您的 HTML。它写一次,就是这样。然后增加 Javascript 变量,但不要相应地更新 HTML,因此更改不可见。
  • @JeremyThille 我该怎么做才能解决这个问题?
  • 每次my_score 更改时重复you.innerHTML= my_score

标签: javascript loops counter increment


【解决方案1】:

由于您在事件处理函数之外分配值,因此在单击发生时不会执行代码(而是在页面加载时使用初始值执行这些代码)。您必须更新事件处理函数中的 HTML。

如果文本是纯文本(不是 htmlString),我建议您使用 innerTexttextContent

尝试以下方法:

var my_score = 0; 
var pc_score = 0;
const you = document.getElementById("You");
const computer = document.getElementById("Computer");
document.getElementById("scissors").addEventListener("click", ()=> {
    playerChoice=scissors;
    computerSelection();
    if (computerChoice == "rock"){
        results.textContent = "It is a loss";
        pc_score++;
    } else if (computerChoice == "paper"){
        results.textContent = "It is a win";
        my_score++;
    }else if (computerChoice=="scissors"){
        results.textContent = "It is a tie";
    }
    you.textContent = my_score;
    computer.textContent = pc_score;
});

【讨论】:

    【解决方案2】:

    您正在更新分数变量,而不是显示该分数的元素的 innerHTML。肯定有更好/更清洁的方法来做到这一点,但只需在更改值后再次调用 computer.innerHTML=pc_scoreyou.innerHTML= my_score

    【讨论】:

    • 改变什么值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2021-06-15
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多