定位类的单个实例

我正在使用CSS隐藏我想在用户点击链接时显示的内容。 页面上有多个实例。

我已经设置了一个示例,但是当前点击任何链接都会显示所有内容。

http://jsfiddle.net/paulyabsley/rHD43/

谢谢

使用.siblings()查找具有类details的元素,该元素是链接父元素的兄弟。

 $('.item h3 a').click(function () { $(this).parent().siblings(".details").toggleClass("display"); });​ 

DEMO

您可以转到根元素并搜索详细信息。

 $(this).parent().parent().find('.details').toggleClass("display"); 

试试这个:

 $('.item h3 a').click(function () { $(this).parent().next().toggleClass("display"); });​ 

在这里演示。

您当前的选择器正在做的是选择匹配的所有元素。 上面的代码片段做的是使用$(this)选择相对于被点击的元素的元素,在这种情况下,这是被点击的

因为

,而

的兄弟,而不是 ,你需要使用$.parent()来选择

,然后使用$.next()获取

之后的下一个元素,即要切换的


更好的方法是将您的点击处理程序绑定到

。 这简化了选择器链,并消除了标签可能带来的任何问题。 这会更好,IMO:

 $('.item h3').click(function () { $(this).next().toggleClass("display"); });​ 

一个稍微复杂一点的解决方案,但它提供了当你打开一个我看到的当前答案缺乏的新描述时关闭其他描述的function。

 $('.item h3 a').click(function () { // always try cache your selectors if you plan on using them repeatedly. var $details = $(this).parent().next("div.details"); if ($details.hasClass('display')){ // if the item we clicked on is already displayed - we want to hide it. $details.toggleClass("display"); }else{ // now we want to close all other open descriptions $("div.details").removeClass("display"); // and only display the one we clicked on. $details.toggleClass("display",true); } });​ 

工作实例

动画示例