我在侧面导航栏中有一个列表,表示页面上的对象.对象的标题与列表中的标题匹配.如下图所示:

我试图使用jQuery显示切换这些对象,以便当用户单击红色列表项(与红色页面对象相同的标题标题)时,相应的页面对象将切换为显示或隐藏.
这是我的简化代码:
// The left navigation list
<ul>
<li>Charity Challenge Golf Outing</li>
<li>Spring 2014 Membership Renewal</li>
<li>EMEA Product Launch</li>
<li>Platinum Customer Retention Spring Offer</li>
<li>Key Account Upsell 2014</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
// A couple of page objects
<div class="single-activity">
<h2>Charity Challenge Golf Outing</h2>
[...]
</div>
<div class="single-activity">
<h2>Spring 2014 Membership Renewal</h2>
[...]
</div>
<div class="single-activity">
<h2EMEA Product Launch</h2>
[...]
</div>
Run Code Online (Sandbox Code Playgroud)
// The jQuery
$(".left-panel li").click(function() {
$(this).toggleClass("selected");
$("#page-content").find(".single-activity").slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
问题:我现在知道它为什么不起作用,但我不确定如何根据<h2>标题"找到"对象.代码可以滑动切换所有对象(因为它们都有.single-activity类,但我只想隐藏单击的那个.任何想法?
你可以使用a filter()或者:contains选择器:
$(".left-panel li").click(function() {
$(this).toggleClass("selected");
$("#page-content").find(".single-activity:contains("+$(this).text()+")").slideToggle();
});
Run Code Online (Sandbox Code Playgroud)
或者filter():
$(".left-panel li").click(function() {
var txt = $.trim( $(this).text() );
$(this).toggleClass("selected");
$("#page-content").find(".single-activity").filter(function() {
return $.trim( $(this).text() ) == txt;
}).slideToggle();
});
Run Code Online (Sandbox Code Playgroud)