与 Facebook 在其新闻源上所做的类似,我想允许对许多源项目进行评论,我通过 php foreach 语句提取这些项目。这是创建相同的类。因此,当我单击 .show_comments 时,它会激活所有内容。
我通过 SO 发现了类似于您在下面看到的东西......但它对我不起作用。
我如何定位单个 .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();
});
});
最佳答案
ID 在 HTML 文档中应该是唯一的。如果您有多个带有 id="show_comments"
的元素,那么您做错了,您将无法通过 Javascript 访问其中的多个。对元素进行分组的正确方法是按类。
假设 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>
然后 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');
});
关于javascript - 如何定位存在相同链接的 jquery 单击函数(即在 php foreach 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/928972/