如何用onclick显示和隐藏一个简单的<ol>列表?

Eri*_*ans 2 html javascript list onclick show

考虑以下段落和列表:

<p id = "list1" onclick = "openList1()">List of Items</p>
<ol>
  <li><a href = "/exampleFolder/file1.txt">List Item 1</a></li>
  <li><a href = "/exampleFolder/file2.txt">List Item 2</a></li>
  <li><a href = "/exampleFolder/file3.txt">List Item 3</a></li>
  <li><a href = "/exampleFolder/file4.txt">List Item 4</a></li>
  <li><a href = "/exampleFolder/file5.txt">List Item 5</a></li>
</ol>
Run Code Online (Sandbox Code Playgroud)

如何使用Javascript显示和隐藏整个列表?

<script>
function openList1() {
...
}
</script>
Run Code Online (Sandbox Code Playgroud)

谢谢你的关注!

moh*_*han 6

您可以为OL列表指定ID .

<p id = "list1" onclick = "openList1()">List of Items</p>
<ol id="ollist">
  <li><a href = "/exampleFolder/file1.txt">List Item 1</a></li>
  <li><a href = "/exampleFolder/file2.txt">List Item 2</a></li>
  <li><a href = "/exampleFolder/file3.txt">List Item 3</a></li>
  <li><a href = "/exampleFolder/file4.txt">List Item 4</a></li>
  <li><a href = "/exampleFolder/file5.txt">List Item 5</a></li>
</ol>
Run Code Online (Sandbox Code Playgroud)

然后在你的JavaScript中你可以像这样切换它...

<script>
function openList1() {
    var list = document.getElementById("ollist");

    if (list.style.display == "none"){
        list.style.display = "block";
    }else{
        list.style.display = "none";
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)