简体   繁体   中英

How do I target a jquery click function where identical links exist (ie within a php foreach)?

Similar to what Facebook does on its newsfeed, I want to allow commenting on numerous feed items, which I'm pulling via a php foreach statement. This is creating identical classes. So when I click .show_comments it activates everything.

I went through SO and found something akin to what you see below...but it's not working for me.

How do I target individual .show_comments to animate and toggle the selected item?

$j(function() {
    $j(this).find('.show_comments').click(function(){
        $j(this).find('.comments').slideDown("fast");
        $j(this).find(".answer_comments").toggle();
    });

    $j(this).find('.hide_comments').click(function(){
        $j(this).find('.comments').slideUp("fast");
        $j(this).find(".answer_comments").toggle();
    }); 
});

IDs should be unique in a HTML document. If you have several elements with id="show_comments" you are doing it wrong and you won't be able to access more than 1 of them through Javascript. The proper way of grouping elements is by classes.

The right way of doing it would then be something like this, assuming the HTML looks like the following:

<div id="item-1">
....text of whatever people are commenting on....
  <a href='#' class='toggle_comments'>show comments</a>
  <div class='comments' style='display: none;'>
  ... comments ...
  </div>
</div>

<div id="item-2">
....text of whatever people are commenting on....
  <a href='#' class='toggle_comments'>show comments</a>
  <div class='comments' style='display: none;'>
  ... comments ...
  </div>
</div>

And the Javascript/jQuery would then be:

$('a.toggle_comments').toggle(function() {
    $(this).next('div.comments').slideDown('fast');
    $(this).text('hide comments');
}, function() {
    $(this).next('div.comments').slideUp('fast');
    $(this).text('show comments');
});

And here is a demo of it in action .

#show_comments is an id and ids need to be unique . when you generate the names/ sections, use something like

id='show_comments1'

and

id='answer_comments1'

to uniquely identify both sections

OR, traverse up the tree from element raising the event to a known parent and then find the answer child and toggle() it

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