JavaScript在PHP循环中不起作用
当我在php中回显结果时,它似乎会在数据库中循环并在下面的“回显”中显示,但如果我尝试使用javascript显示它,它甚至不会循环。javascript中有什么问题JavaScript在PHP循环中不起作用,javascript,php,html,loops,while-loop,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 ?>
<?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
}
?>
html中的ID不是唯一的。除此之外,元素必须存在才能通过ID获取。@jeroen好的,那么除了getElementById和document.write之外,还有没有其他方法可以在javascript中“回送”变量?我不知道为什么你要为此引入JS,而不是直接输出HTML,但是,如果您觉得必须让PHP输出一个值数组,然后在PHP循环之后,让一些JS使用数组中的数据来创建适当的HTML元素,那么有100种方法。但是,通常情况下,您会使用php创建元素,并使用echo语句输出它们,或者使用php if语句确定何时显示元素或元素的一部分。使用var all_data=,获取数组中的所有行,并一次发送它们代码>将是我的选择。是否仍有调用此函数的方法:“document.getElementById(“test”).innerHTML=callJSFunction()”?每次单击时都应尝试使用click调用它。