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

JavaScript猜谜游戏输入验证异常:错误答案被判定正确,如何修复?

猜谜游戏答案验证问题修复

我做了一个基础猜谜游戏,从对象数组中随机抽取谜题展示给玩家,玩家输入答案后进行验证,但现在存在错误——错误的答案会被判定为正确。我是JavaScript新手,检查过语法、if语句逻辑和输入验证,还是没能解决问题,相关代码如下:

原代码

JavaScript

$(document).ready(function() {
  let riddles = [{
      question: 'What word contains all of the twenty-six letters?',
      answer: 'alphabet'
    },
    {
      question: 'Which word in the dictionary is spelled incorrectly?',
      answer: 'incorrectly'
    },
    {
      question: 'What color can you eat?',
      answer: 'orange'
    },

    {
      question: 'What has a head, a tail, is brown, and has no legs?',
      answer: 'penny'
    },
    {
      question: 'I’m tall when I’m young, and I’m short when I’m old. What am I?',
      answer: 'candle'
    },
    {
      question: 'What can travel around the world while staying in a corner?',
      answer: 'stamp'
    },
    {
      question: 'What has keys but can’t open locks?',
      answer: 'piano'
    },
    {
      question: 'What has one eye but can’t see?',
      answer: 'needle'
    }

  ];

  $('.startBtn').on('click', function() {
    // Select and display a random riddle
    let selectedRiddle = riddles[Math.floor(Math.random() * riddles.length)];
    $('.theRiddle').text(selectedRiddle.question);
    $('.result').empty();
  });

  $('.submitBtn').on('click', function() {
    let playerGuess = $('.answer-section').val();

    if (playerGuess === '') {
      $('.result').text('Please guess or enter "quit" to exit.');
    } else {
      let selectedRiddle = $('.theRiddle').text();

      if (playerGuess.toLowerCase() === 'quit') {
        $('.result').text('Thanks for playing! Goodbye.');
        $('.theRiddle').empty();
      } else if (playerGuess.toLowerCase() !== selectedRiddle.answer) {
        $('.result').text('Incorrect answer. Try again.');
      } else(playerGuess.toLowerCase() === selectedRiddle.answer)
      $('.result').text('CORRECT! You win!\nThe answer is: ' + playerGuess);
      $('.theRiddle').empty();
    }

  });
});

CSS

.riddleSection {
  height: 100%;
  margin-top: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.answer-section {
  padding-left: 170px;
  padding-right: 170px;
  padding-top: 30px;
  padding-bottom: 30px;
  border-radius: 30px;
}

.answer-section input::placeholder {
  color: #999;
  font-style: italic;
  text-align: center;
}

.submitBtn,
.startBtn {
  width: 120px;
  height: 40px;
  border-radius: 10px;
  border: none;
  margin-top: 10px;
  background-color: lightblue;
}

.startBtn:hover,
.submitBtn:hover {
  background-color: dimgray;
}

.theRiddle {
  margin-top: 80px;
  text-align: center;
  letter-spacing: 5px;
  font-size: 30px;
}

.headingOne {
  margin: 0;
  text-align: center;
  letter-spacing: 9px;
  font-size: 80px;
}

.result {
  text-align: center;
  letter-spacing: 5px;
  font-size: 50px;
}

HTML

<!-- heading section -->
<h1 class="headingOne">Riddle Game</h1>


<!-- riddle appears here -->
<p class="theRiddle"></p>

<!-- answer section -->
<div class="riddleSection">
  <input class="answer-section" placeholder="Enter your answer">
  <button class="submitBtn">Submit</button>
  <button class="startBtn">Start Game</button>
</div>

<div class="result"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

问题原因分析

  1. 核心逻辑错误:提交按钮事件中,let selectedRiddle = $('.theRiddle').text(); 将谜题文本(字符串)赋值给了selectedRiddle,后续尝试访问selectedRiddle.answer会得到undefined,导致答案比较逻辑完全失效。
  2. 语法错误:else(playerGuess.toLowerCase() === selectedRiddle.answer) 写法错误,else不能附带条件,且后续代码没有用大括号包裹,导致无论答案正确与否,都会执行「正确」的提示代码。

修复后的代码

JavaScript(已汉化并修复逻辑)

$(document).ready(function() {
  let riddles = [{
      question: '哪个单词包含全部26个字母?',
      answer: 'alphabet'
    },
    {
      question: '字典里哪个单词拼写错误?',
      answer: 'incorrectly'
    },
    {
      question: '什么颜色可以吃?',
      answer: 'orange'
    },
    {
      question: '有头有尾,棕色,没有腿,是什么?',
      answer: 'penny'
    },
    {
      question: '我年轻时很高,老了就变矮,我是什么?',
      answer: 'candle'
    },
    {
      question: '什么东西能环游世界却一直待在角落?',
      answer: 'stamp'
    },
    {
      question: '什么有钥匙却打不开锁?',
      answer: 'piano'
    },
    {
      question: '什么有一只眼睛却看不见?',
      answer: 'needle'
    }
  ];

  // 存储当前选中的谜题对象
  let currentRiddle = null;

  $('.startBtn').on('click', function() {
    // 随机选择谜题并存储对象
    currentRiddle = riddles[Math.floor(Math.random() * riddles.length)];
    $('.theRiddle').text(currentRiddle.question);
    $('.result').empty();
    $('.answer-section').val(''); // 清空输入框
  });

  $('.submitBtn').on('click', function() {
    let playerGuess = $('.answer-section').val().trim();

    if (playerGuess === '') {
      $('.result').text('请输入答案,或者输入"quit"退出游戏。');
      return;
    }

    // 处理退出逻辑
    if (playerGuess.toLowerCase() === 'quit') {
      $('.result').text('感谢游玩!再见。');
      $('.theRiddle').empty();
      currentRiddle = null;
      $('.answer-section').val('');
      return;
    }

    // 检查是否已获取谜题
    if (!currentRiddle) {
      $('.result').text('请先点击「开始游戏」获取谜题!');
      return;
    }

    // 答案验证(忽略大小写)
    if (playerGuess.toLowerCase() === currentRiddle.answer.toLowerCase()) {
      $('.result').text(`正确!你赢了!\n答案是:${currentRiddle.answer}`);
      $('.theRiddle').empty();
      currentRiddle = null;
      $('.answer-section').val('');
    } else {
      $('.result').text('答案错误,再试一次!');
    }
  });
});

HTML(已汉化)

<!-- 标题区域 -->
<h1 class="headingOne">猜谜游戏</h1>

<!-- 谜题展示区域 -->
<p class="theRiddle"></p>

<!-- 答案输入区域 -->
<div class="riddleSection">
  <input class="answer-section" placeholder="输入你的答案">
  <button class="submitBtn">提交</button>
  <button class="startBtn">开始游戏</button>
</div>

<!-- 结果展示区域 -->
<div class="result"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

CSS代码可直接沿用原代码,无需修改。

关键修改点

  • 新增currentRiddle全局变量存储当前选中的谜题对象,确保提交时能正确获取对应答案。
  • 修复else语法错误,用标准的if-else分支处理答案验证逻辑。
  • 增加输入内容的trim()处理,避免空格导致的误判。
  • 补充「未开始游戏时提交」的提示逻辑,提升用户体验。
  • 统一大小写比较,避免因大小写差异导致的错误判定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:04:53