简体   繁体   English

如何在存在相同链接的情况下(例如,在php foreach中)定位jquery click函数?

[英]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. 类似于Facebook在其新闻提要上所做的事情,我想允许对众多提要项进行评论,这是通过php foreach语句提取的。 This is creating identical classes. 这将创建相同的类。 So when I click .show_comments it activates everything. 因此,当我单击.show_comments时,它将激活所有内容。

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? 如何针对单个.show_comments设置动画并切换所选项目?

$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. ID在HTML文档中应该是唯一的。 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. 如果您有多个id="show_comments"元素,则id="show_comments"您做错了,您将无法通过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: 假设HTML如下所示,那么正确的做法将是这样的:

<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: 然后,JavaScript / jQuery将是:

$('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 . #show_comments是一个ID,且ID必须是唯一的 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 或者,从引发事件的元素上遍历树到已知的父级,然后找到答案子级并将其toggle()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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