将TD悬停在while循环中时如何获取特定ID

时间:2019-11-21 14:52:41

标签: php mysql ajax

当悬停特定的td时,我应该获得唯一的timecard_id_overtime,但是我总是在while循环中得到最后一个id。我尝试使用id而不是class,但这也不起作用。非常感谢。

<?php include "../db_connection302.php" ; ?>
<?php

         echo"<tr>" ;
         echo"<th class='leave-heading'>Particular </th>" ;
         echo"</tr>" ;


         // GENERATING ALL PENDING ATTENDANCE FOR APPROVAL 
         $query  = "SELECT * FROM ".$_SESSION['$company_code']."_tms WHERE  status = 'Pending' AND (particular = 'Log In' || particular = 'Log Out' || particular = 'Log In/Out' || particular = 'OB' || particular = 'Offsetting' ) ";
         $result_approval = mysqli_query($connection302,$query) or die(mysql_error());
         while($row_approval = mysqli_fetch_array($result_approval))  { 

         echo "<tr>" ;
         echo "<td class='reason'>".$timecard_id_overtime = $row_approval['timecard_id']."</td>" ;
         echo "</tr>" ;

             }

?>  

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


     var timecard_id = '<?php  echo $timecard_id_overtime  ; ?>' ;   


     $(document).ready(function() {


             $('.reason').hover(function() {

                 alert(timecard_id) ;


             });



         });



 </script>

1 个答案:

答案 0 :(得分:1)

在您的while循环中,您每次循环迭代都会覆盖相同的值$timecard_id_overtime,因此在循环完成时它将始终是最后一个值。

$timecard_id_overtime的值每次都会被覆盖。

//first iteration
//$timecard_id_overtime is set to 1

//second iteration
//$timecard_id_overtime is set to 2

//third iteration
//$timecard_id_overtime is set to 3

...等等。

一种实现目标的方法是为每个循环使用<td>设置ID,以便将正确的ID与正确的元素相关联。您可以将该ID设置为<td>元素的属性,而不是PHP变量。然后,JQuery可以轻松获得该值。

...
PHP
...
 while($row_approval = mysqli_fetch_array($result_approval))  { 

     echo "<tr>" ;
     echo "<td class='reason' timecard_id='".$row_approval['timecard_id']."'></td>" ;
     echo "</tr>" ;

         }
...
Javascript
...
 $(document).ready(function() {

         $('.reason').hover(function() {
             alert($(this).attr('timecard_id')) ;
         });
     });
...
...