我有这样的情况:
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("commentDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
和 php 代码
<?php
echo "<table><tr onclick='myFunction()'><td>Row A1</td></tr>"; //A1 row from my table
echo "<tr><td><div id='commentDIV' style='display:none'> Row B1</div></td></tr></table>"; // the B1 row show after click on the A1
?>
当我单击第一行第二个外观时,一切正常。
在这种情况下如何使用/修改我的 javascript 函数?
<?php
$x=0;
while($x<10){
echo "<table><tr onclick='myFunction()'><td>Row A$x</td></tr>"; //Ax row from my table
echo "<tr><td><div id='commentDIV' style='display:none'> Row B$x</div></td></tr></table>"; // the Bx row must show after click on the Ax
$x++;
}
?>
请帮助并拯救我的日子! 非常感谢!
最佳答案
问题是您对所有 Div 使用相同的 id“commentDIV”,因此您应该更改循环和函数。
- 将
$x
添加到最初称为commentDIV
的 divid
- 更改
myFunction
调用以包含$x
数字 - 将 id 参数添加到
myFunction
定义 - 将传递的 ID 附加到
getElementById
值
像这样:
<?php
$x=0;
while($x<10){
echo "<table><tr onclick='myFunction($x)'><td>Row A$x</td></tr>";
// ^^--- 2. add $x
echo "<tr><td><div id='commentDIV_$x' style='display:none'> Row B$x</div></td></tr></table>";
// ^^^--- 1. add $x
$x++;}
?>
JavaScript 代码更改为:
<script type="text/javascript">
function myFunction(id) {
// ^^--- 3. add id
var x = document.getElementById("commentDIV_" + id);
// ^ ^^^^^--- 4. append id
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
关于php 循环的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51367026/