根据匹配的ID和类别定位要显示/隐藏的元素 [英] Targeting elements to show/hide based on matching ids and classes

查看:85
本文介绍了根据匹配的ID和类别定位要显示/隐藏的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 <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.

Thanks in advance for any help.

解决方案

To present an alternative solution which should be more efficient than @David's answer:

$('li.archive-month > a').live('click', function()
{
    $(this).parent().nextUntil('.archive-month').toggle();
    return false;
});

You can even do a bit better by using .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;
});

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 <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.

这篇关于根据匹配的ID和类别定位要显示/隐藏的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆