unique id for dynamic table

£可爱£侵袭症+ 提交于 2021-01-29 08:26:36

问题


I will be generating a HTML table with data pulled from MySQL.The number of rows in my MySQL table are not fixed.

<?php
  while($row=mysql_fetch_assoc($result))
  { ?>
    <tr>
      <td><?php echo $row['col1'];?></td>
      <td><?php echo $row['col2'];?></td>
    </tr>
  <?php } ?>

Now how do I have the table rows and table data elements assigned unique id ??

Another loop to generate them won't work as I can't set an exit condition for the new loop as number of rows are not fixed.

Please guide me as to how to go forward about it. I can only use Javascript and not JQUERY.


回答1:


Why can't you do something like this ?

<?php
  $i = 1;
  while($row=mysql_fetch_assoc($result))
  { ?>
    <tr id="row<?php echo $i;?>">
      <td id="cell-left-<?php echo $i;?>"><?php echo $row['col1'];?></td>
      <td id="cell-right-<?php echo $i;?>"><?php echo $row['col2'];?></td>
    </tr>
  <?php
     $i++;
   } ?>

Please note, I have added ids row, cell-left- and cell-right- by myself. You may change them as per your requirements.




回答2:


You can use a counter when iterating through the rows, maybe something like this:

<?php
    $rowCount = 0;

    while($row=mysql_fetch_assoc($result))
    {
        $rowCount++;
        ?>
        <tr id="<?php echo 'row' . $rowCount;?>">
            <td><?php echo $row['col1'];?></td>
            <td><?php echo $row['col2'];?></td>
        </tr>
        <?php
    }

?>

You can now select an element with

var rowID = 1;
document.getElementById("row" + rowID);

Hope this helps.



来源:https://stackoverflow.com/questions/17521990/unique-id-for-dynamic-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!