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

Quiz应用单题展示功能异常:超5题时全部显示的原因排查

问题原因分析与解决方案

问题根源

你的Quiz应用在题目数量超过5道时一次性展示所有题目,核心原因是JavaScript中隐藏题目的逻辑完全错误:

在你的JS代码里,hider = i + count这个计算逻辑完全不符合“仅显示当前题目”的需求。当题目数量≤5时,可能因为后续的question_xxx元素不存在,误打误撞让大部分题目被隐藏;但当题目数量超过5后,这个计算无法覆盖中间的题目,导致所有题目默认处于显示状态。

举个例子:当有6道题时,count=6,循环中i从0到5:

  • i=0时,hider=0+6=6 → 只会隐藏#question_6,而#question_2到#question_5依然显示
  • 后续i值计算出的hider都会大于6,对应的元素不存在,无法隐藏任何题目
    最终所有题目都会被展示出来。

修复后的代码

修正JavaScript逻辑

$(document).ready(function() { 
  var steps = $('form').find(".questions"); 
  var count = steps.length; // 替换已废弃的size()方法
  // 页面加载时,默认只显示第一个题目,隐藏其他所有题目
  steps.not(':first').hide();

  steps.each(function(i) { 
    var currentStepNum = i + 1;
    // 最后一题绑定提交事件
    if (currentStepNum === count) { 
      $("#next" + currentStepNum).on('click', submit); 
    } else { 
      createNextButton(currentStepNum); 
    } 
  }); 

  function submit() { 
    $.ajax({ 
      type: "POST", 
      url: "ajax.php", 
      data: $('form').serialize(), 
      success: function(msg) { 
        $("#quiz_form,#demo1").addClass("hide"); 
        $('#result').show(); 
        $('#result').append(msg); 
      } 
    }); 
  } 

  function createNextButton(currentStep) { 
    var nextStep = currentStep + 1;
    $('#next' + currentStep).on('click', function() { 
      $("#question_" + currentStep).hide(); 
      $("#question_" + nextStep).show(); 
    }); 
  } 

  setTimeout(submit, 50000); 
}); 

优化PHP代码(修复SQL注入风险+完善结构)

<?php
$response = $db->prepare("select * from questions WHERE test_ID = :test_id"); 
// 使用参数绑定防止SQL注入
$response->bindParam(':test_id', $_POST['test_ID']);
$response->execute(); 

echo "<form method='post' id='quiz_form'>"; 
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL); 

$count = 1; 
while($result=$response->fetch(PDO::FETCH_ASSOC)) { 
    // 确保每个题目容器带有正确的class和id
    echo "<div class='questions' id='question_$count'>";
    echo "<p>" . htmlspecialchars($result['question_text']) . "</p>";
    // 这里添加你的选项、输入框等内容
    echo "<button type='button' id='next$count'>Next</button>";
    echo "</div>";
    $count++;
}
// 不要忘记关闭form标签
echo "</form>";
?>

额外注意事项

  1. 原JS中的steps.size()方法已被jQuery废弃,建议改用steps.length。
  2. 你的PHP代码存在严重的SQL注入风险,必须使用参数绑定替代直接拼接POST参数。
  3. 确保PHP循环中正确关闭了<form>标签,否则HTML结构错误会影响JS选择器的正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:15:29