【问题标题】:JavaScript does not work inside PHP loopJavaScript 在 PHP 循环中不起作用
【发布时间】:2016-11-03 09:23:25
【问题描述】:

似乎当我在 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
}
?>

【问题讨论】:

  • html 中的 ID 不能是唯一的。除此之外,元素必须存在才能通过 ID 获取。
  • @jeroen 好的,那么除了 getElementById 和 document.write 之外,还有其他方法可以在 javascript 中“回显”变量吗?
  • 我不知道你为什么要为此引入 JS 而不是直接输出 HTML,但是如果你觉得你必须为什么不让 PHP 输出一个值数组,然后在PHP循环有一些JS使用数组中的数据来创建适当的HTML元素?
  • 有 100 种方法。然而,通常你会使用 php 创建元素,并使用 echo 语句来输出它们,或者使用 php if 语句来确定何时显示元素或元素的一部分。
  • 获取数组中的所有行并使用 var all_data = &lt;?php echo json_encode($your_php_array); ?&gt;; 一次性发送它们是我的选择。

标签: javascript php html loops while-loop


【解决方案1】:

请试试这个

<?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
    }
  ?>

【讨论】:

  • 是否有在此调用函数:"document.getElementById("test_=$id?>").innerHTML = callJSFunction()" ?
  • 你应该尝试每次点击它都会被调用。
猜你喜欢
  • 2013-07-06
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多