I have the following (basically, schedule_box
is the wrapper, and there can be as many client_schedule
divs as needed). I have .details
hidden by default, and I want the details
to show when the down arrow is clicked:
<div class="schedule_box">
<div class="client_schedule">
<span class="edit">
<img src="images/manage_companies/down-icon.png" class="down">
</span>
<span class="details">
test
</span>
</div>
<div class="client_schedule">
<span class="edit">
<img src="images/manage_companies/down-icon.png" class="down">
开发者_开发知识库 </span>
<span class="details">
test
</span>
</div>
</div>
JQuery (when I use the entire contact box, it works):
$('.schedule_box').find('.details').hide().end().find('.down').click(function() {
}
But, when I try to use .down
, it's having problems finding .details
:
$('.schedule_box').find('.details').hide().end().find('.down').click(function() {
var details = $(this).find('.details');
if (details.is(':visible')) {
details.slideUp();
} else {
details.slideDown();
}
});
try
var details = $(this).parents('.client_schedule').find('.details');
You need to use find
in the context of appropriate ".client_schedule"
parent div:
var details = $(this).parent('.client_schedule').find('.details');
That's because this
inside click event handler is the image being clicked -- and obviously it doesn't have ".details"
div as its descendant. Its parent ".client_schedule"
div, on the other hand, has.
You want to find the next sibling of the parent of .down
:
var details = $(this).parent().next();
Alternatively, you could go all the way up to .client_schedule
and find .detail
:
var details = $(this).closest(".client_schedule").find(".detail");
Note: You want to use .closest()
with this approach and not .parent()
or .parents()
. .parent()
retrieves only the immediate parent, and .parents()
ought to have been named .ancestors()
because it retrieves every ancestor that matches the selector. .closest()
gives you the first ancestor that matches the selector.
You could always do a little event delegation by assigning the handler directly to .client_schedule
elements, and testing what was clicked.
$('.client_schedule').click(function( e ) {
if( $(e.target).is('img.down') ) {
var details = $(this).find('.details');
if (details.is(':visible')) {
details.slideUp();
} else {
details.slideDown();
}
}
}).find('.details').hide();
You can also use the slideToggle()
[docs] method to reduce the code a little:
Example: http://jsfiddle.net/REJ6Z/
$('.client_schedule').click(function( e ) {
if( $(e.target).is('img.down') ) {
$(this).find('.details').slideToggle();
}
}).find('.details').hide();
精彩评论