使用jQuery进行元素定位

Esp*_*noy 2 jquery

我试图使用jQuery在用户单击"a"元素时显示div.我正在努力,因为我无法准确地瞄准div.

查看下面的代码,您会看到我的程序列出了优惠(优惠#1和优惠#2).在商品div的正下方,有注释div(显示商品的评论).可以单击.comment_icon元素来显示/隐藏注释.

<div id="offer">
Offer#1 goes here
<a href="#" class="comment_icon">Show comments</a>
</div>
<div class="comments">
Comments for Offer#1 goes here
</div>

<div id="offer">
Offer#2 goes here
<a href="#" class="comment_icon">Show comments</a>
</div>
<div class="comments">
Comments for Offer#2 goes here
</div>

$('.comment_icon').toggle(
    function() {
        $('.comments').slideDown();
    },
    function() {
        $('.comments').slideUp();
    }
);
Run Code Online (Sandbox Code Playgroud)

我的问题是,当单击.comment_icon元素时,它将显示带有.comments类的所有div.但是,我只想在单击.comment_icon时显示属于相应商品的商品.

有没有办法做这种tartgeting?

Dou*_*ner 6

首先,你不应该使用两个相同的元素id,但只是说你保持这种方式,这就是你想要的:

$('.comment_icon').click(function(e){
  $(this).closest('div#offer').next('.comments').slideToggle();
  e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

就像我说的,要更改id='offer'class='offer',然后就改变选择在我的答案div.offer.