我尝试使用 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();
}
);
我的问题是,当单击 .comment_icon 元素时,它将显示带有 .comments 类的所有 div。但是,我只想在单击 .comment_icon 时显示属于相应报价的报价。
有什么方法可以进行这种目标定位吗?
最佳答案
首先,您不应该使用具有相同 id
的两个元素,但我们可以保持这种方式,这就是您想要的:
$('.comment_icon').click(function(e){
$(this).closest('div#offer').next('.comments').slideToggle();
e.preventDefault();
});
就像我说的,您想将 id='offer'
更改为 class='offer'
,然后只需将我的答案中的选择器更改为 div .报价
.
关于jquery - 使用 jQuery 定位元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038467/