显示基于类的元素

时间:2011-09-28 20:58:17

标签: jquery

我有像这样的HTML

 <h2 class="Comprehensive Leadership">Comprehensive Leadership</h2><a href="/topic/comprehensiveleadership">View all Comprehensive Leadership Programs </a>
 <br><a href="/programs/pld/Pages/default.aspx" class="Comprehensive Leadership">Program for Leadership Development &gt;</a><br>Dec 2011–Jun 2012<br><a href="/programs/gmp/Pages/default.aspx" class="Comprehensive Leadership">General Management Program &gt;</a><br>Jan–May 2012<br>


<h2 class="Corporate Governance">Corporate Governance</h2><a href="/topic/corporategovernance">
View all Corporate Governance Programs </a><br><a href="/programs/ac/Pages/default.aspx" class="Corporate Governance">Audit Committees in a New Era of Governance &gt;</a><br>Nov 13–15, 2011<br><a href="/programs/cc/Pages/default.aspx" class="Corporate Governance">Compensation Committees &gt;</a><br>Nov 16–18, 2011<br>

<div class="tabbed-content"><ul class="tabs"><li><ul><li><a href="#" class="Comprehensive Leadership">Comprehensive Leadership</a></li><li><a href="#" class="Corporate Governance">Corporate Governance</a></li><div>

如果我单击Comprehensive Leadership,它应该只显示第一个h2标记,方法是将该类匹配到下一个h2标记,即:

<h2 class="Comprehensive Leadership">Comprehensive Leadership</h2><a href="/topic/comprehensiveleadership">View all Comprehensive Leadership Programs </a>
 <br><a href="/programs/pld/Pages/default.aspx" class="Comprehensive Leadership">Program for Leadership Development &gt;</a><br>Dec 2011–Jun 2012<br><a href="/programs/gmp/Pages/default.aspx" class="Comprehensive Leadership">General Management Program &gt;</a><br>Jan–May 2012<br>

我可以改变html一点......我也在这里粘贴它:http://jsfiddle.net/sMCsw/10/

2 个答案:

答案 0 :(得分:0)

更好的解决方案不是按类选择,而是使用此选择H2的实际值:

function showByText(text){
    $("h2:contains('" + text + "')").show();
    // added a return false to prevent the a href from actually executing
    return false;
}
<a href="/programs/pld/Pages/default.aspx" onclick="return showByText(this.text();">Comprehensive Leadership</a>

答案 1 :(得分:0)

html的结构方式不适合轻松解决这个问题。我不认为它甚至值得花时间试图用你当前的html结构弄清楚它而不首先知道你是否可以修改它。如果你可以修改它,那么这是一个非常容易的问题。

现在你有这样的结构:

<h2>Topic</h2>
... a bunch of content....
<h2>Topic2</h2>
... a bunch of content....

您要求的链接除了点击的主题外都隐藏所有内容。但是您没有容器来定义您的内容。您需要包含内容块,以便隐藏/显示它们。

<div class="mytopic">
<h2>Topic</h2>
   ... a bunch of content....
</div>
<div class="mytopic2">
<h2>Topic2</h2>
   ... a bunch of content....
</div>

然后你可以构造一个jQuery构造函数来隐藏除了想要的内容之外的所有内容。正如评论中的某些人已经指出的那样 - 课程Comprehensive Leadership与您使用它的方式是非法的。修复它。

$('div').not('.mytopic').hide();

重新阅读本文时,我认为您可能实际上想要显示内容,而不是隐藏它。很难说你发布的代码不完整而且你没有提供CSS。无论如何,如果你想要展示,那么这个jQuery系列将起作用。

$('div.mytopic').show();