简体   繁体   中英

Toggle a repeated class in jQuery

I have this HTML code:

<div id="content">
  <div class="profile_photo">
   <img style="float:left;margin-right:7px;" src="http://gravatar.com/avatar/53566ac91a169b353a78b329bdd35c95?s=50&d=identicon" class="profile_img" alt="{username}"/>
  </div>
  <div class="container" id="status-#">
   <div class="message">
    <span class="username">{username} Debugr Rocks!
   </div>
   <div class="info">24-oct-2010, 14:05 GMT · <a href="#" class="toggle_comment" title="Comment">Comment (5)</a> · <a href="#" title="Flag" class="toggle_flag">Flag</a> · Via <a href="#" title="Twitter">Twitter</a>
</div>
   <div class="comment_container">
    <div class="profile_photo">
     <img style="float:left;margin-right:7px;" src="http://gravatar.com/avatar/53566ac91a169b353a78b329bdd35c95?s=32&d=identicon" class="profile_img" alt="{username}"/>
    </div>
    <div class="comment_message">
     <span class="username"><a href="#" title="{username}">{username}</a></span> Debugr Rocks! XD
    </div>
    <div class="comment_info">24-oct-2010</div>
   </div>
  </div>
  <div class="profile_photo">
   <img style="float:left;margin-right:7px;" src="http://gravatar.com/avatar/53566ac91a169b353a78b329bdd35c95?s=50&d=identicon" class="profile_img" alt="{username}"/>
  </div>

That is repeated two or more times . What I want to do, is to when I click the "Comments (5)" link, the class "comment_container" appears, but only the one in the same "container" class.

It's this possible?

You can use .closest() to go up to the .container then .find() to look inside it, like this:

$(".toggle_comment").click(function() { 
    $(this).closest(".container").find(".comment_container").show();
});

You can try it here , if you're curious about finding other things relative to this here's a full list of the Tree Traversal functions .


As an aside, there's an error in your HTML that needs correcting, this:

<span class="username">{username} Debugr Rocks! </div>

Should be:

<span class="username">{username} Debugr Rocks! </span>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM