0

这是检查被单击的收音机以与结果进行比较并向上滑动的脚本:

<script>
$(document).ready(function(){
   $("input:radio").change(function(){
      checkResult(this);
   });  
});

function checkResult(el)
{
   //get the radio button value
   var clickedvalue=$(el).val() ;

   $this=$(el).parent("div.QA");
   var hiddenanswer=$this.find(".hidden_result").val();

   //call to next function to check result
   var report=checkAnswer(clickedvalue,hiddenanswer);
   if(report)
   {
      $this.find(".report").html("correct");
   }
   else{
      $this.find(".report").html("Incorrect");
   }

function checkAnswer(click,answer){
   if(click==answer){
      return true;
   }
   else{
      return false;
   }
}

   $this.delay(500).slideUp();

}

</script>

这是从数据库中获取问题和选项的PHP 。我使用时间戳name为每个问题(收音机)设置不同的名称。

<?php     
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database"); $query="select * from question_answer ";
$result=mysqli_query($dbconnect,$query);
?>

<form method="get" action="">
<div id="container">

<?php       
while($rows=mysqli_fetch_array($result))
{
   echo '<div class="QA">';
   echo '<h1>'.$rows['question'].'</h1>'.'<br/>';
   echo '<input type="radio" class="check" name="'.$rows['radioname'].'" value="A">'.$rows['option1'].'</input>';
   echo '<input type="radio" class="check" name="'.$rows['radioname'].'" value="A">'.$rows['option2'].'</input>';
   echo '<input type="radio" class="check" name="'.$rows['radioname'].'" value="A">'.$rows['option3'].'</input>';
   echo '<input type="radio" class="check" name="'.$rows['radioname'].'" value="A">'.$rows['option4'].'</input>';
   echo '<br/>';
   echo '<div class="report"></div>';
   echo'</div>';
}  
?>

</div>
</form>
4

1 回答 1

0

现在我已经正确缩进了您的代码,我可以看到您缺少}CheckResult 函数的关闭。

function checkResult(el)
{
   ...
   else{
      $this.find(".report").html("Incorrect");
   }
} // <- this is missing!

缩进代码是个好主意,因为这样更容易阅读和查找此类错误。我也会在您放置开口和闭合牙套的方式上保持一致 - 选择一种风格并坚持下去。我不知道这是否仍然是这种情况,但是当您将左大括号放在这样的行尾时,JavaScript 会更有效:

function checkResult(el){
   //get the radio button value
   var clickedvalue = $(el).val();

   $this = $(el).parent("div.QA");
   var hiddenanswer = $this.find(".hidden_result").val();

   //call to next function to check result
   var report = checkAnswer(clickedvalue,hiddenanswer);
   if(report){
      $this.find(".report").html("correct");
   }else{
      $this.find(".report").html("Incorrect");
   }
}

另一个提示,您可以通过执行以下操作来简化 checkAnswer 函数:

function checkAnswer(click,answer){
    return (click==answer); // this will return true or false
}

但是根据点击和回答的值范围是什么,您可能希望使其更加健壮并检查无效值。

我还鼓励您研究 PHP 中的heredoc语法——这是处理长字符串的好方法,尤其是当它们同时包含单引号和双引号时。这是一个关于它的S/O 问题

于 2013-08-15T03:49:28.510 回答