jQuery toggle elements with class in parent div on

2019-06-06 05:17发布

问题:

I've been beating my head against my desk for the last two days over this one. I'm making an app that displays info from a db, the title/link, thumbnail, and time saved wrapped in an unordered list, like so: http://blog.madebycraig.com/images/full.jpg
What I'm trying to do is have a minimize button on the element, toggling the thumbnail and time saved on and off: http://blog.madebycraig.com/images/minimized.jpg
I can accomplish this, but it's all or nothing. I click one minimize button, and everything goes. How can I contain it to just toggle items with a certain class name that are children of the div that the minimize button is in? I've tried .parent(), .child(), .next(), .prev(). I've thrown everything at it that I know. Now I turn to you, kind sirs (or madams). What am I doing wrong? Here's the ul I'm trying to run it on.

echo'
<li class="bookmarkContainer">
<a href="'.$row['url'].'" class="toggle"><img class="thumb" src="images/placeholder.png" /></a>
<div class="title"><a href="'.$row['url'].'" class="bookmrk" target="_blank">'.$row['title'].'</a></div>
<div class="dt toggle">'.relativeTime($row['dt']).'</div><br />
<a class="collapse" href="#">hide</a>
<a class="delete" href="?delete='.$row['id'].'" id="'.$row['id'].'">Delete Bookmark</a>
</li>';

回答1:

You can do it using .closest() and .find() like this:

$(".collapse").click(function() {
  $(this).closest('.bookmarkContainer').find('.toggle').toggle();
});

If you have lots of these, or they are changing via ajax (seems like a search-resulty thing), use .live() or .delegate() like this:

$(".collapse").live('click', function() {
  $(this).closest('.bookmarkContainer').find('.toggle').toggle();
});
//or...
$("#ulID").delegate('.collapse', 'click', function() {
  $(this).closest('.bookmarkContainer').find('.toggle').toggle();
});