Show/Hide script using javascript

本小妞迷上赌 提交于 2019-11-29 11:09:28

Suppose this is your code:

<a href="#" onclick="toggle_visibility('list1');">
  <p>List One</p>
</a>
<div id="list1" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>
<a href="#" onclick="toggle_visibility('list2');">
  <p>List Two</p>
</a>
<div id="list2" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>

Change it to this:

<a href="#" onclick="toggle_visibility('list1');">
  <p>List One</p>
</a>
<div id="list1" class="alist" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>
<a href="#" onclick="toggle_visibility('list2');">
  <p>List Two</p>
</a>
<div id="list2" class="alist" style="display:none;">
  <ul>
    <li>Item One</li>
    <li>Item Two</li>
    <li>Item Three</li>
  </ul>
</div>

And make your JavaScript this:

function toggle_visibility(id) {
    var list = document.getElementsByClassName("alist");
    for (var i = 0; i < list.length; i++) {
        list[i].style.display = 'none';
    }
    var e = document.getElementById(id);
    if(e.style.display == 'block') {
        e.style.display = 'none';
    } else {
        e.style.display = 'block';
    }
}

Here's a JSFiddle.

Instead of using plain JavaScript for this, I suggest you use jQuery.

Here's how I would do it in jQuery:

function toggle_visibility(id) {
  $(".list").hide();
  $("#" + id).toggle();
}

I would add one more function to hide all the lists but one current:

function toggle_visibility(id) {
    var e = document.getElementById(id);
    if (e.style.display == 'block') e.style.display = 'none';
    else e.style.display = 'block';

    hideAllBut(id);
}

function hideAllBut(id) {
    var lists = document.querySelectorAll('.list');
    for (var i = lists.length; i--; ) {
        if (lists[i].id != id) {
            lists[i].style.display = 'none';
        }
    }
}

http://jsfiddle.net/q2E5e/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!