建议 #1
给所有的标题元素一个通用的类名,例如title
,然后使用document.getElementsByClassName('title')
来查找所有的标题元素,如果单击的标题元素被隐藏,则在“取消隐藏”单击的标题之前将它们全部隐藏。
话虽如此,您需要修改您编写的两个函数以在一个元素中容纳多个类。您可以通过 轻松设置多个类名element.className = 'unhidden title'
,但您的代码将相当不灵活。当您尝试通过该String#split
方法修改类名列表时,您的代码将很快变得笨拙,遍历类以查找和删除隐藏或未隐藏的类。
建议#2
Do not to use an unhidden class. Presumably, your unhidden class is defined as follows:
.unhidden {
display: block;
}
This class becomes much less useful if you have inline elements as well that you want to unhide because you'll need another class:
.unhidden-inline {
display: inline;
}
If you simply define:
.hidden {
display: block;
}
and add or remove the hidden class to hide or show the element, then you can avoid this issue altogether. You'll still have the issue of dealing with multiple class names in an element, however.
Suggestion #3 (ideal)
Use jQuery or Zepto.js to handle DOM traversal and manipulation, it will make your life much easier. You'll no longer need to manipulate classes at all in this case, you can simply hide and show the elements directly with convenience methods. Include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
Assuming the following markup:
<ul>
<li class="title">
Title 1
<div class="description">Best. Title. Ever.</div>
</li>
<li class="title">
Title 2
<div class="description">Second best title</div>
</li>
<li class="title">
Title 3
<div class="description">Worst. Title. Ever.</div>
</li>
</ul>
and the following css:
<style type="text/css">
.description {
display: none;
}
</style>
you can do the following to accomplish your goal in a flexible manner:
<script type="text/javascript">
$('.title').click(function(event){
currentDescriptionElement = $('.description', this); // this refers to the clicked DOM element in this context
isHidden = currentDescriptionElement.is(':hidden');
$('.title .description:visible').hide(); // hide all visible description elements
if (isHidden)
currentDescriptionElement.show();
})
</script>
I hope this helps, good luck!