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

答题游戏点击下一题时函数执行次数倍增问题求助

问题分析与解决方案

核心问题原因

  • 事件绑定重复累加:每次调用trivia()时,都会给#next、#true、#false元素重新绑定click事件。第一次调用绑定1次,第二次调用又绑定1次,导致点击时多个事件处理函数同时执行,出现执行次数倍增的现象。
  • 题目索引重复选取:newNumber()函数每次执行都会重新生成包含0-9的数组,再随机返回一个值,无法避免重复选中同一道题。
  • 答案标记逻辑冲突:重复绑定的点击事件会导致旧的标记逻辑依然生效,出现所有答案被错误标记的情况。

修复方案

  1. 将事件绑定移到trivia()外部:只绑定一次事件,避免重复累加。通过变量存储当前题目索引,在事件处理函数中更新索引并刷新题目。
  2. 重构题目索引生成逻辑:一次性生成不重复的随机索引数组,按顺序取用,确保10道题不重复。
  3. 简化状态清除逻辑:直接移除所有答案元素的right和wrong类,无需复杂判断。

修复后的代码

$(document).ready(function() {
  let currentIndex = 0;
  let questionIndices = [];
  let triviaData = null;

  // 生成不重复的随机题目索引数组
  function generateQuestionIndices() {
    while (questionIndices.length < 10) {
      const randomNum = Math.floor(Math.random() * 10);
      if (!questionIndices.includes(randomNum)) {
        questionIndices.push(randomNum);
      }
    }
  }

  // 渲染当前题目
  function renderTrivia() {
    const i = questionIndices[currentIndex];
    const question = triviaData.results[i].question;
    const rightAnswer = triviaData.results[i].correct_answer;
    const wrongAnswer = triviaData.results[i].incorrect_answers[0];

    $('#question').html(question);

    // 根据正确答案设置按钮文本和点击逻辑
    if (rightAnswer === 'True') {
      $('#true').text('True').off('click').on('click', function() {
        $(this).addClass('right').siblings('.answer').removeClass('right wrong');
      });
      $('#false').text(wrongAnswer).off('click').on('click', function() {
        $(this).addClass('wrong').siblings('.answer').removeClass('right wrong');
      });
    } else {
      $('#false').text('False').off('click').on('click', function() {
        $(this).addClass('right').siblings('.answer').removeClass('right wrong');
      });
      $('#true').text(wrongAnswer).off('click').on('click', function() {
        $(this).addClass('wrong').siblings('.answer').removeClass('right wrong');
      });
    }
  }

  // 切换下一题
  function nextQuestion() {
    // 清除所有答案的状态类
    $('.answer').removeClass('right wrong');
    // 更新当前索引,循环或结束(可根据需求调整逻辑)
    currentIndex = (currentIndex + 1) % 10;
    renderTrivia();
  }

  // 绑定下一题按钮事件(只绑定一次)
  $('#next').on('click', function(event) {
    event.preventDefault();
    nextQuestion();
  });

  // 请求数据并初始化游戏
  $.get('https://opentdb.com/api.php?amount=10&category=17&type=boolean', function(dados) {
    triviaData = dados;
    generateQuestionIndices();
    renderTrivia();
  });
});

关键优化点说明

  • 事件绑定优化:使用.off('click')先移除旧的点击事件,再绑定新的,避免重复绑定;同时将#next的事件绑定移到API请求外部,只执行一次。
  • 索引管理优化:一次性生成不重复的索引数组,通过currentIndex跟踪当前题目位置,确保每道题只出现一次。
  • 状态清除简化:直接调用$('.answer').removeClass('right wrong')清除所有状态,替代冗余的判断逻辑。
  • 代码结构拆分:将生成索引、渲染题目、切换题目拆分为独立函数,提高代码可读性和可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:54:22