jQuery toggle elements with class in parent div only

有些话、适合烂在心里 提交于 2019-12-23 01:40:09

问题


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();
});


来源:https://stackoverflow.com/questions/2965718/jquery-toggle-elements-with-class-in-parent-div-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!