在现有的<li>中添加<ul>

时间:2018-07-28 14:31:45

标签: javascript jquery html twitter-bootstrap

<!DOCTYPE html>
<html>
<body>

<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a>
  <ul>
  <li>profile</li>
  <li>details</li>
  </ul></li>
</ul>


</body>
</html>

我的标题中有一个简单的li作为菜单。我只是想添加子列表,就像单击about时应该显示子列表一样。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您可以通过更改其About属性(display将其隐藏并display: none来显示),使其最初处于隐藏状态并在单击display: block时显示它。

<!DOCTYPE html>
<html>
<body>

  <ul>
    <li><a href="#home">Home</a></li>
    <li><a href="#news">News</a></li>
    <li><a href="#contact">Contact</a></li>
    <li><a href="#about" onClick="showAbout()">About</a>
      <ul style="display: none;" id="about">
        <li>profile</li>
        <li>details</li>
      </ul>
    </li>
  </ul>
  <script>
    function showAbout() {
      document.getElementById("about").style.display = "block";
    }
  </script>

</body>
</html>

如果您想切换About子菜单的可见性,则可以在每次单击display时检查About子菜单的About属性。

<!DOCTYPE html>
<html>
<body>

  <ul>
    <li><a href="#home">Home</a></li>
    <li><a href="#news">News</a></li>
    <li><a href="#contact">Contact</a></li>
    <li><a href="#about" onClick="showAbout()">About</a>
      <ul style="display: none;" id="about">
        <li>profile</li>
        <li>details</li>
      </ul>
    </li>
  </ul>
  <script>
    function showAbout() {
      var about = document.getElementById("about");
      if (about.style.display === "none") {
        about.style.display = "block";
      } else {
        about.style.display = "none";
      }
    }
  </script>

</body>
</html>

答案 1 :(得分:1)

您可以根据情况add remove class

$("a").on("click",function(e){
 if($(e.target).attr('href') == '#about'){
    $("#add").addClass('show');
    $("#add").removeClass('hide');
 }
})
.hide{
    display: none;
}
.show{
 display:block;
}
#add{
    position:absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a>
  <ul id="add" class="hide" >
  <li>profile</li>
  <li>details</li>
  </ul></li>
</ul>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

编辑。单击后,您想在文本上方显示ul