javascript - 如何在单击下一步按钮时一一显示数组的元素?

标签 javascript php jquery

我尝试了很多解决方案,但它们都不符合我的目的。 这是我的完整 PHP 工作代码,用于仅为单个数字生成随机表达式。

      <?php
      error_reporting(E_ALL & ~E_NOTICE);
           if(isset($_POST['play']))
        {
       //validation for no of operation selected
       $operation = $_POST['operation'];
       if(empty($operation)) 
             {
               echo "Please Select at least one operation <br/>";
             }
              else
              {  
                 $N = count($operation); //count selected operation
              ?>
              <div class="slideshow-container" id="slide">
                 <center>
                  <?php 
                    echo  "<br />";
                    echo "<span style= 'font-size: 20px;'><i>This is your generated sequence !<br><br></span>";
                    echo "<span style= 'font-size: 18px;'><i>You have selected $N operation(s):"; 

                     for($i=0; $i < $N; $i++)  //for loop for for operator array.
                        {
                          echo($operation[$i] . ", "); //display selected operation
                        }
                        echo "<br />";
                   ?>                              
                </center>
              </div>
                  <?php
                     //checkbox operations
                    if($N==1)   //if only one operation is selected
                        {
                             if($operation[0]=='Addition')
                                 {
                                      $rOperators = array('+');                           
                                 }
                                else if($operation[0]=='Subtraction')
                                   {
                                      $rOperators = array('-');
                                    }
                                    else if($operation[0]=='Multiplication')
                                      {
                                      $rOperators = array('*');
                                       }
                                        else
                                          {
                                            $rOperators = array('/');
                                          }
                        }
                    else if ($N==2) //if only two operations are selected by the user
                     {
                        if($operation[0]=='Addition')
                            {
                                if($operation[1]=='Subtraction')
                                    {
                                        $rOperators = array('+','-');
                                    }
                                     else if($operation[1]=='Multiplication')
                                         {
                                           $rOperators = array('+','*');
                                         }
                                          else
                                             {
                                               $rOperators = array('+','/');
                                             }                           
                            }
                            else if($operation[0]=='Subtraction')
                            {
                                if($operation[1]=='Multiplication')
                                     {
                                        $rOperators = array('-','*');
                                     }
                                    else
                                      {
                                        $rOperators = array('-','/');
                                      }
                            }
                              else
                                {
                                  $rOperators = array('*','/');
                                }
                      }
                        else if ($N==3) //if 3 o
                            {
                                if($operation[0]=='Addition')
                                 {
                                     if($operation[1]=='Subtraction')
                                         {
                                             if($operation[2]=='Multiplication')
                                             {
                                                 $rOperators = array('+','-','*');    
                                             }
                                             else
                                             {
                                                 $rOperators = array('+','-','/');
                                             }

                                         }
                                      else
                                         {
                                              $rOperators = array('+','*','/');
                                         }                         
                                 }
                                 else
                                 {
                                     $rOperators = array('-','*','/');
                                 }
                            }
                        else
                            {
                                $rOperators = array('+','-','*','/');
                            }                            
             }
       //display sequence having only single digit numbers
         if($_POST['digits'] == 1)
        {
        $q = $_POST['que'];
             $previousInt = null;        //Track the previous operand
             $s = $_POST['select'];

              //display inputs given by user through form
             ?>
             <div class="slideshow-container" id="slide">
             <center>
              <?php 
              echo "<span style= 'font-size: 18px;'><i>No.of questions:".$q. "<br />";
              echo "<span style= 'font-size: 18px;'><i>No. of integers:" .$s. "<br />";
              echo  "<span style= 'font-size: 18px;'><i>No of digits: 1 <br />";
              ?>                    
              </center>
              <?php
                     for ($x = 1; $x<=$q; $x++) //for loop for no. of questions
                        {
                           $randomOperands = array();
                            $randomOperators = array();

                                    // loop over $i n times
                                   for ($i = 1; $i <=$s; $i++) //for loop for no. of integers user entered
                                     {
                                        $nextInt = rand(1, 9); // assign random operand to array slot
                                         $randomOperands[] = $nextInt;
                                            if($i < $s)
                                             {   
                                               if($previousInt === 0) //No operator after last opearnd
                                                  {
                                                 //avoid division-by-zero
                                                   $randomOperators[] = $rOperators[rand(0, 2)];
                                                  }
                                                else
                                                  {
                                                   $randomOperators[] = $rOperators[rand(0, $N-1)];
                                                  } 
                                              }  
                                        $previousInt = $nextInt;
                                      }

                                    // print array values:
                                   $exp = '';  
                                      $output_string = " ";
                                          //Generating the expression
                                           foreach($randomOperands as $key=>$value1)
                                         {
                                          $exp .=  $value1 . "" ;
                                             $output_string .= $value1."<br>";
                                             if(isset($randomOperators[$key]))
                                                {
                                                 $exp .=  $randomOperators[$key]  ."";
                                                  $output_string .= $randomOperators[$key]."<br>";
                                                }

                                         }
                                          //print expression

                                          $res = eval("return ($exp);");//evaluate the expression
                                           $generate = array($output_string, $res);
                    ?> 
                         <div class="mySlider">

                         <!--  go back to previous element of expression , for inner slider-->
                                          <a class="back" id= "pre" onclick="addSlides(-1)" style="float: left; top: 46%; position: absolute; right: 800px; cursor: pointer; font-size: 27px;">❮</a>

                                 <!--display of the expression-->
                                           <cemter>  <?php
                                              echo '<span style= "font-size: 27px;"<br>Q('.$x.')<br><br>'.$output_string.'</span><br>';             
                                             ?>

                                   <!-- generate result with show button-->  
                                         <div class="ansdiv"><?php echo '<span style= "font-size: 27px;"<br>____<br>'.$res."<br>"; ?></div><br></cemter>

                                      <!--  go to next element of expression , for inner slider-->
                                    <a class="front" id = "fro" onclick="addSlides(1)" style="float: right; top: 46%; position: absolute; left: 800px; cursor: pointer; font-size: 27px;">❯</a>    
                             </div>
            <?php   } ?>
                             <center><input type="button" name="show" value="*****" id="show">
                                      <!-- eye icon for show answer-->
                                      <img src="Images/Eye.png" id = "open"></center>
        <?php   } 
         ?>                      </div>
                           <a class="prev" id= "prev" onclick="plusSlides(-1)">Previous</a>
                           <a class="next" id = "next" onclick="plusSlides(1)">Next</a>
                   <div class="dot-container">
                         <span class="dot" onclick="currentSlide(1)"></span> 
                         <span class="dot" onclick="currentSlide(2)"></span> 
                         <span class="dot" onclick="currentSlide(3)"></span> 
                     </div>
       <?php
        }
       ?> 
                               <script>
                //script for generate one by one questions
              var slideIndex = 1;
              showSlides(slideIndex);
                function plusSlides(n) 
                  {
                    showSlides(slideIndex += n);
                  }

                function currentSlide(n) 
                    {
                      showSlides(slideIndex = n);
                    }

               function showSlides(n) {
                   var i;
                   var slides = document.getElementsByClassName("mySlider");
                   var dots = document.getElementsByClassName("dot");
                    if (n > slides.length) {slideIndex = 1}    
                    if (n < 1) {slideIndex = slides.length}
                     for (i = 0; i < slides.length; i++)
                         {
                          slides[i].style.display = "none";  
                         }
                     for (i = 0; i < dots.length; i++) 
                     {
                       dots[i].className = dots[i].className.replace(" active", "");
                     }
                       slides[slideIndex-1].style.display = "block";  
                        dots[slideIndex-1].className += " active";
                     }
               </script>

               <script>
                                        //shw answer on clicking show button 
                                         $(document).ready(function(){
                                           //show when eye icon clicked
                                          $("#open").click(function(){  
                                             $(".ansdiv").toggle();
                                           }); 
                                          //show when show button clicked
                                          $("#show").click(function(){  
                                             $(".ansdiv").toggle();
                                           });
                                          $("#next").click(function(){  
                                             $(".ansdiv").hide();
                                           });
                                          });
                            </script>

这是我的表格

        <body>
    <?php if(!isset($_POST['play'])) 
      {
       ?>
<div class="main-container">


        <h3><I>GENERATE HERE !</I></h3>
          <form action="" method="POST">
              <div class="row">
                 <div class="col-25">
                   <label for="qnum">Select no.of questions:</label>
                    </div>
                     <div class = "col-75"><input type="number" id="qnum" name="que" value="1"  min="1" max="100"></div>
                     <br /><br />
               </div>
             <br />

        <div class="row">
              <div class="col-25">
                <label for="int">How many numbers you want in a sequence? :</label></div>
                    <div class="col-75">
                       <select name="select" id="int">
                        <option value="2"> 2 </option>
                        <option value="3"> 3 </option>
                        <option value="4"> 4 </option>
                        <option value="5"> 5 </option>
                        <option value="6"> 6 </option>
                        <option value="7"> 7 </option>
                        <option value="8"> 8 </option>
                        <option value="9"> 9 </option>
                        <option value="10"> 10 </option>
                      </select>
                    </div>
      </div>
      <br /> 

       <div class="row">
           <div class="col-25">
             <label for="dig">Select no. of digits:</label></div>
                <div class="col-75">
                  <select name="digits" id="dig">
                   <option value="1"> 1 Digit </option>

                   </select>
              </div>
              <br /><br /><br />
        </div>

          <div class="row">
          <div class="col-25"><label>Select operations:</label><br /></div>
              <div class="col-75">
                <input type="checkbox" id="mix" value="all" class="toggle-button"><label>All</label>
                <input type="checkbox" id="add" name="operation[]" value="Addition" checked><label>Addition</label>
                <input type="checkbox" id="sub" name="operation[]" value="Subtraction"><label>Subtraction</label>
                <input type="checkbox" id="mult" name="operation[]" value="Multiplication"><label>Multiplication</label>
                <input type="checkbox" id="div" name="operation[]" value="Division"><label>Division</label>
               </div>
                <br /><br />
                <br /><br />
            </div><br />


        <input type="button" name="submit" value="Generate" id="gen"><br>
        <input type="submit" name="play" value="Play" id="play">
        <br><br>
         <br />
 </form>
  </div>
    <script language="JavaScript">
      $( '.col-75 .toggle-button' ).click( function () {
          $( '.col-75 input[type="checkbox"]' ).prop('checked', this.checked)
      })
    </script>

                <script>
                    $(document).ready(function(){
                      $("#show").click(function(){  
                         $(".ansdiv").show();
                             });
                          });
                </script> 
      </center>

      <script>
                    $(document).ready(function(){
                      $("#gen").click(function(){  
                         $("#play").show();
                           $("#gen").hide();
                             });
                          });
                </script> 



  <?php } 
    include 'operate.php'; 
    ?>
  </body>

这是我得到的输出截图:

enter image description here

如您在屏幕截图中所见,表达式正在生成及其结果。 $output_string 是表达式,$res 是表达式的结果。它们都存储在名为 $generate 的数组中。

现在我想在单击下一步按钮时一个一个地显示数组的所有元素,即根据屏幕截图第一个元素应该是 4 并且在单击下一步按钮之后,应该有 - 运算符等等,直到结果显示在最后。

注意 - 这里每次 $output_string 变量的值都会不同,因为表达式是随机生成的,因此结果也会改变。这对我的目的来说工作正常,但我尝试了很多解决方案,但我无法以某种方式一一显示元素。

我该如何解决?请帮助我。

最佳答案

使用种子随机生成器生成随机数:http://php.net/manual/en/function.srand.php 使用种子随机生成器,您可以生成一个随机数序列,该随机数对于特定的种子值始终相同。

您可以在表单中有一个隐藏字段,它会告诉您什么是种子值,这将确保您能够为该种子创建相同的随机序列。

// Picks a random element from $array
function get_random_item($array) {
    $array_length = count($array);
    if ($array_length) {
        return $array[rand(0, $array_length - 1)];
    }
    return null;
}

// Generates a random digit
function generate_random_digit() {
    return rand(0, 9);
}

// Generates a random number that has $num_digits
function generate_random_operand($num_digits) {
    $operand = "";
    while ($num_digits--) {
        $operand += generate_random_digit();
    }
    return $operand;
}

// Generates a simple algebraic expression in form of an array
function generate_expression($num_operands, $operators, $max_digits = 1) {
    $expression = array();
    while ($num_operands--) {
        $expression[] = generate_random_operand($max_digits);
        if ($num_operands) {
            $expression[] = get_random_item($operators);
        }
    }
    return $expression;
}
// On server request, you would then:
// 1. read the values from the $_POST array
// 2. set the random seed using the seed variable sent via POST params
// 3. generate the expression
// 4. render your view
function render_expression() {
    $seed = $_POST['seed'] ?? rand();
    $num_operands = $_POST['s'] ?? 2;
    $operators = array_map(function($operation_name) {
        // this map function converts array that looks like:
        //    ['Addition', 'Multiplication']
        // into an array that looks like
        //    ['+', '*']
        switch($operation_name) {
            case 'Subtraction': 
                return '-';
            case 'Multiplication':
                return '*';
            case 'Division':
                return '/';
            case 'Addition': 
                // fall through to default
            default: 
                return '+';
        }
    }, $_POST['operation'] ?? []);
    $expression = generate_expression($num_operands, $operators);
    echo implode(" ", $expression);
}

为了一一显示操作数,单击按钮后,您可以有另一个隐藏的表单字段,该字段将保留操作数计数器的值,然后呈现该变量指示的那么多表达式操作数。

不过,我建议在客户端执行此操作。像这样:

function showNextHiddenItem(btn) {
  var nextHiddenSpan = this.parentNode.parentNode.querySelector('span.hidden');
  if (nextHiddenSpan) {
    nextHiddenSpan.classList.remove('hidden');
  }
}

[...document.querySelectorAll('button.next')].forEach(button => button.addEventListener('click', showNextHiddenItem));
.expression span.hidden {
  display: none;
}
<div class="expression">
  <span class="hidden">4</span>
  <span class="hidden">-</span>
  <span class="hidden">2</span>
  <span class="hidden">+</span>
  <span class="hidden">5</span>
  <span class="hidden">*</span>
  <span class="hidden">8</span>
  <span class="hidden">=</span>
  <span class="hidden">42</span>
  <div><button class="next">Next</button></div>
</div>

关于javascript - 如何在单击下一步按钮时一一显示数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53476129/

相关文章:

javascript - 如何使用 Ajax 和 JSON 制作下拉菜单?

javascript - 使用 WebGL 将两个 Canvas 混合到一个 Canvas 上

Javascript/ES6 从一级对象生成嵌套数组

javascript - jQuery - 防止默认,然后继续默认

javascript - 双击 Bootstrap 图标时防止事件触发

javascript - 点击时的 cytoscape.js 平移和 z-index/foregrounding 元素

php - 将 html 表单 cloumn 数组转换为行 php

PHP PDO 准备语句查询不更新记录

php - 统一命名方案问题: SQL column names and PHP array keys casing schemes conflict

javascript - 单击某个项目时出现错误查询切换打开所有 div?