JavaScript 在 PHP 循环中不起作用

标签 javascript php html loops while-loop

似乎当我在 php 中回显结果时,它会循环遍历数据库并将其显示在下面的“回显”中,但如果我尝试使用 javascript 显示它,它甚至不会循环。 javascript 有什么问题?

<?php
while($row = $result->fetch()){
    $id = $row['id'];

    echo $id; //loops through and displays the all the id's in order in the database
    ?>

    //this only displays the first id and doesn't loop even though it is in the php while loop
    <script>
        document.getElementById("test").innerHTML = "<?= $id ?>";
    </script>
    <span id="test"></span>

    <?php
}
?>

最佳答案

请试试这个

<?php

while($row = $result->fetch()){
$id = $row['id'];

echo $id; //loops through and displays the all the id's in order in the database
?>

//this only displays the first id and doesn't loop even though it is in the php while loop

 <!-- change in id name -->
<span id="test_<?=$id?>"></span>

<script type="text/javascript">
   //change here
    document.getElementById("test_<?=$id?>").innerHTML = "<?= $id ?>";
</script>
<?php
    }
  ?>

关于JavaScript 在 PHP 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137372/

相关文章:

javascript - JavaScript 中的点击事件未触发

javascript - 为什么这个表达式在 JavaScript 中被评估为 "a"?

php - 错误消息 URL 参数导致重复内容

php - 如何在 PHP 中使用 "file_put_contents"访问文件?

php - json 编码 � 值变为空

javascript - 使用 html 和 javascript 在鼠标单击和按键时调用相同的函数

html - 如何将表单内容放在 Bootstrap 的同一行中

javascript - 如何将 html 页面的标题插入到 anchor 标记的文本中?

javascript - 你能记录其他人使用 swagger 开发的 API 吗?

html - Twitter "Follow"按钮在 Bootstrap 中导致水平滚动条