根据匹配的ID和类别定位要显示/隐藏的元素 [英] Targeting elements to show/hide based on matching ids and classes
问题描述
Jquery的新手,想知道是否有人可以帮助我解决以下问题:
使用文本模式,我已经生成了一个列表;
<li class="archive-month"><a href="#" id="May2011">May</a></li>
<li class="May2011"><a rel="bookmark" href="http://***">Post Number One</a></li>
<li class="May2011"><a rel="bookmark" href="http://***">Post Number Two</a></li>
<li class="May2011"><a rel="bookmark" href="http://***">Post Number One</a></li>
<li class="archive-month"><a href="#" id="April2011">April</a></li>
无限次.
我的问题是,如何使用<a>
标签显示和隐藏具有与标签ID相匹配的类的列表项?例如,单击ID为"May2011"的a
可以切换隐藏和显示所有匹配类为"May2011"的li
,依此类推.
在此先感谢您的帮助.
提出一种替代解决方案,该解决方案比 ad infinitum. My question is, how can I use the Thanks in advance for any help. To present an alternative solution which should be more efficient than @David's answer: You can even do a bit better by using N.B. this does not use element IDs at all. Instead it relies on the HTML structure being consistent with what's in the OP — namely that the 这篇关于根据匹配的ID和类别定位要显示/隐藏的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<a>
tags to show and hide the list items with classes that match the id of the tag? For example, click on the a
with an id of "May2011" to toggle hiding and showing of all li
with a matching class of "May2011" and so on for the various months.$('li.archive-month > a').live('click', function()
{
$(this).parent().nextUntil('.archive-month').toggle();
return false;
});
.delegate()
instead of .live()
if all the <li>
s share a common ancestor - a <ul>
, perhaps.$('#some-common-ancestor').delegate('li.archive-month > a', 'click', function()
{
$(this).parent().nextUntil('.archive-month').toggle();
return false;
});
<li>
s that should be toggled when a link is clicked are the next siblings of the parent of the link, up to but not including the next li
with class archive-month
.