用jQuery切换类
当用户点击链接时,我需要隐藏div。
html是这样的:
Lorem ipsum Show/hide comments Lorem ipsum Show/hide comments ....there's multiple items after this
默认情况下,注释是隐藏的(因此隐藏了类)。 现在,如果用户单击“显示/隐藏评论”链接,则应显示或隐藏该特定项目的评论,具体取决于它们是否可见。 现在问题是我需要一些id来控制js只挂钩到那个特定的项目ocmments并且我可以用id做吗?
js就像atm:
$('.item .commentsToggle').click(function(){ elem = $(this).parents('.item'); $(elem).find('.comments').each(function() { $(this).toggleClass('hidden'); }); });
如果只有一个项目有效,但多个项目分解:/
这很简单..我只是不知道如何实际做到这一点:D
试试这个JS:
$('.commentsToggle').click(function(){ $(this).siblings(".comments").toggleClass('hidden'); });
如果你保留每个post的当前结构,最简单的方法是
$('.item .commentsToggle').click(function(){ $(this).next().toggleClass('hidden'); });
但是更普遍的方式就像你在暗示的那样
$('.item .commentsToggle').click(function(){ $(this).closest('.item').find('.comments').toggleClass('hidden'); });
另请注意,您应该使用.on()
函数来绑定jQuery 1.7中的事件,即使旧函数仍然有效。
我会这样做
$('.item .commentsToggle').click(function(){ $(this).next('.comments').toggleClass('hidden'); });
如果您有更多评论,可以使用以下内容
$('.item .commentsToggle').click(function(){ $(this).closest('.item').children('.comments').toggleClass('hidden'); });