I created a ul
containing li
elements. I want to to slide down a div
when a link in the same li
is clicked.
The problem is when I click the link all div
s are shown.
I use PHP for setting the id on each link.
The html code is here:
<li class='post'>
<div class='link'>
<a href='#'id=". * Here is Post ID * ."></a>
</div>
<div class='slidedown'>//here is what I want to sliding</div>
</li>
The jQuery code is here :
$(".link a").click(function(){
var id_post = $(this).attr("id");
$(".slidedown").slideDown("slow");
return false;
});
Use .parent()
to move up one parent. Since the container were looking for is the .post
we'll have to move up 2 parents. Then we can find the child of it that is .slidedown
and slide that one down with .slideDown()
$(".link a").click(function(){
$(this).parent().parent().children('.slidedown').slideDown("slow");
});
You can do it even more easy:
jQuery
$('.link').on('click', function() {
$(this).parent().find('.slidedown').slideDown('slow');
});
Or you use:
$('.link a').on('click', function() {
$(this).closest('.slidedown').slideDown('slow');
});
Go to .closest() or .parent() at jQuery Docs to learn more.
Here's the code that works well:
$(".link").click(function(){
$(this).siblings('.slidedown').slideDown('slow');
});
You can use parent()
to move up a level and next()
to target the next sibling:
$(".link a").click(function(){
$(this).parent(".link").next(".slidedown").slideDown("slow");
return false;
});
Or you can access the .post
using closest()
and target the .slidedown
using find()
or children()
:
$(".link a").click(function(){
$(this).closest(".post").find(".slidedown").slideDown("slow");
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.