开发者

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_开发者_如何学Cinfo">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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜