When clicking the I want this particular .parents ul to open and all other to collapse. Below code does not work for me.
I think I do not understand how I use this and misuse e in the below code.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/der/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var selected;
$(".parents").click(function(){
selected = this.id;
// Open list
$("#" + selected + " ul").css("display", "block");
// Remember opened list
$.cookie('tree', '#' + this.id);
// Cycle through all lists
$(".parents").each(function(e){
开发者_运维问答 // Collapse all children that does not
// belongs to the opened list
if(e.id != selected) {
$("#" + e.id + " ul").css("display", "none");
}
});
});
});
</script>
<style type="text/css">
.child_list {
display: none;
}
</style>
</head>
<body>
<ul id="tree">
<li class="parents" id="parent_1"><a href="#">Parent 1</a>
<ul class="child_list">
<li class="child"><a href="#">Child 1</a>
<li class="child"><a href="#">Child 2</a>
<li class="child"><a href="#">Child 3</a>
</ul>
</li>
<li class="parents" id="parent_2"><a href="#">Parent 2</a>
<ul class="child_list">
<li class="child"><a href="#">Child 1</a>
<li class="child"><a href="#">Child 2</a>
<li class="child"><a href="#">Child 3</a>
</ul>
</li>
</ul>
</body>
</html>
Instead of re-selecting things, find them relative to this
, the item you clicked on, like this:
$(function(){
$(".parents").click(function(){
// Open list
$(this).find("ul").show();
// Remember opened list
$.cookie('tree', '#' + this.id);
// Cycle through all lists
$(this).siblings().find("ul").hide();
});
});
You can give it a try here (everything but cookie). You could also give it a bit of animation by using .slideUp()
and .slideDown()
instead of .hide()
and .show()
, check that option here.
The above approach uses tree traversal, so you start with the <li>
you clicked on, then move around to find what you wanted, e.g. other .siblings()
to close their children, etc.
Change
$(".parents").each(function(e){
// Collapse all children that does not
// belongs to the opened list
if(e.id != selected) {
$("#" + e.id + " ul").css("display", "none");
}
});
to
$(".parents").each(function(){
// Collapse all children that does not
// belongs to the opened list
id = $(this).attr('id');
if(id != selected) {
$("#" + id + " ul").css("display", "none");
}
});
e
usually refers to an event but as your only cycling elements there's no event there, so within each element you can use this instead.
精彩评论