You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用click EventListener实现石头剪刀布时玩家输入变量为空如何解决?

石头剪刀布游戏变量空值问题修复方案

问题原因

你在if、else分支中重复用let声明了playerOneInput和playerTwoInput,这两个是仅在分支作用域内有效的局部变量,你对外层全局声明的同名变量没有做任何赋值操作,所以最终调用比对函数时拿到的还是初始的空值。

修复代码

把分支里的let关键字删除,直接给外层变量赋值即可,修改后的JS逻辑如下:

const options = document.querySelectorAll(".options");
var timesClicked = 0;

console.log(options);

let playerOneInput = "";
let playerTwoInput = "";

options.forEach((option) => {
    option.addEventListener("click", function () {
        timesClicked++;
        console.log(timesClicked);

        if (timesClicked == 1) {
            // 去掉let,直接给外层变量赋值
            playerOneInput = this.textContent;
            document.getElementById("player").innerHTML = "Player 2, choose your option!"
        } else {
            // 去掉let,直接给外层变量赋值
            playerTwoInput = this.textContent; 
        };
        
        console.log(playerOneInput);
        console.log(playerTwoInput);

        if (timesClicked == 2) {
            compareInputs(playerOneInput, playerTwoInput);
            // 可选补充:一轮比对完成后重置计数和变量,方便开启下一轮游戏
            // timesClicked = 0;
            // playerOneInput = "";
            // playerTwoInput = "";
            // document.getElementById("player").innerHTML = "Player 1, choose your option!"
        }

    });
    
});

你现有HTML代码无需修改,调整JS的赋值逻辑即可正常运行。

内容的提问来源于stack exchange,提问作者Herman Vulkers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:54:03