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();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…