Javascript显示/隐藏的困难

difficulty with Javascript show/hide

本文关键字:隐藏 显示 Javascript      更新时间:2023-09-26

我在php中有一个foreach循环,通过目录搜索,找到任何其他目录,然后在javascript中使用hide/show,子目录名称被制作成下拉的链接,以显示特定子目录内的文件。我希望这能说得通。我遇到的问题是,因为我使用循环来查找任何现有的子目录,我不能给每个子目录一个不同的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>

一种方法是使用计数器并使用它来改变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>