如何在jquery中使用php while循环中生成的唯一id

How to use unique ids generated in a php while loop in a jquery

本文关键字:循环 id 唯一 while php jquery      更新时间:2023-09-26

有人能帮我解决这个问题吗?我使用while循环从MySQL数据库中生成了一些具有唯一id的数据。

while ($row = mysql_fetch_array($query)){
  echo'<tr>
    <td><img src="expand.png" id="$row['id']"></td>
    <td>'.$row['name'].'
      <div id="'.$row['id'].'_Expanded">
        //some data regarding the selected id need to be displayed here
      </div>     
 </td>
</tr>';
} 

我希望div在页面加载时隐藏,但当我单击图像时,只有一个与id相关的div应该在JQuery中展开。

有人能帮我检索JQuery中要使用的单个ID吗。谢谢

看看这个例子:(我通过foreach数组硬编码了您的mysql获取循环)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <style type="text/css">
    .expandable{
      display: none;
    }
  </style>
  <script type="text/javascript">
  $(function(){ // onload
    $('.expandableContainer img').click(function(){
      $('#'+this.id+'_Expanded').toggle();
    });
  });
  </script>
</head>
<body>
<table>
<?php
$data = [
  ['id' => 1, 'name' => 1],
  ['id' => 2, 'name' => 2],
  ['id' => 3, 'name' => 3],
  ['id' => 4, 'name' => 4],
];
foreach ($data as $row){?>
  <tr class="expandableContainer">
    <td><img src="expand.png" id="<?php echo $row['id']; ?>"></td>
    <td><?php echo $row['name']; ?>
      <div id="<?php echo $row['id']; ?>_Expanded">
        //some data regarding the selected id need to be displayed here
      </div>
    </td>
  </tr>
<?php } ?>
</table>
</body>
</html>