0

我在 php 中有一个 foreach 循环,它搜索一个目录,找到任何其他目录,然后在 javascript 中使用隐藏/显示,子目录名称被制作成下拉链接以显示该特定子目录内的文件。我希望这是有道理的。我遇到的问题是,因为我使用循环来查找任何现有的子目录,所以我不能给每个子目录一个不同的 id。结果,所有链接都具有第一个链接的 id,并且当其中任何一个被单击时,第一个链接总是下降。我需要为此使用 JQuery 吗?

<!--Code for the javascript part:-->
<?php
<script language="javascript">
    function showOrHide(){ 
        var div = document.getElementById("showOrHideDiv");
        if (div.style.display == "block"){ 
                div.style.display = "none";
        }
        else {
            div.style.display = "block";
        }
    }
</script>
?>

<!-- A subdirectory has been found and is called $subDir -->
<!-- Below is the show/hide part of my html/php code -->

<a href="javascript:showOrHide();"><?php echo $subDir;?></a>
<div id="showOrHideDiv" style="display: none">

<!-- The rest of the code that prints the files from the subdirectory -->

</div>
4

1 回答 1

2

一种方法是使用计数器并使用它来改变 ID:

<a href="javascript:showOrHide(<?php echo $counter;?>);"><?php echo $subDir;?></a>
<div id="showOrHideDiv_<?php echo $counter;?>" style="display: none">

然后你的javascript改变:

<script language="javascript">
  function showOrHide(num){ 
    var div = document.getElementById("showOrHideDiv_" + num);
    if (div.style.display == "block"){ 
      div.style.display = "none";
    }
    else {
      div.style.display = "block";
    }
  }
</script>
于 2013-05-30T21:48:34.527 回答