使用jQuery创建扩展列表时出现问题

Trouble creating an expanding list with jQuery

本文关键字:问题 列表 jQuery 创建 扩展 使用      更新时间:2023-09-26

我需要为我的客户的播客存档页面列出一个列表,该页面会打开,显示他们点击的当月不同播客的链接。我非常想要BlogSpot在页面右侧为其默认博客存档小部件提供的东西:http://kimrome.blogspot.com/

我能在这里做出这样的东西:http://thehummingbirdplace.com/test2.html但我不知道如何制作箭头来显示列表是否已扩展。因此,它需要在单击时更改方向,并在再次单击时返回到上一个方向以关闭该部分。

当我打开页面时,我的版本也会显示子元素,我不希望它们在点击父元素之前展开

我在网上查看了一下是否已经创建了jQuery来做这件事,或者我如何才能做到这一点,但由于我不确定整件事的标题是什么,所以我得到了好坏参半的结果。任何帮助都将不胜感激!!

尝试jQuery UI手风琴

$(...).accordion();

,或此:http://jsfiddle.net/5SKLV/1/

$(...).myAccordion();

根据自己的喜好编写CSS即可。

如果你想自己做这件事(自己写东西很有趣(:

我已经向根<ul>添加了一个ID #tree,并将级别1 <li>的文本包装在<span>:中

<ul id="tree">
    <li>
        <span>parent1</span>
        <ul>
            <li>child11</li>
            <li>child12</li>
        </ul>
    </li>
    <li>
        <span>parent2</span>
        <ul>
            <li>child21</li>
            <li>child22</li>
        </ul>
    </li>
</ul>

要应用向左和向右指向父元素的箭头,请创建两个具有背景的CSS类,例如(您需要在其他地方找到背景图像或自己制作(:

.opened > span {
    background: url('arrow_pointing_down.png') left top;
    color: #0a0; /* just to make it easy to know which class it has */
}
.closed > span {
  background: url('arrow_pointing_right.png') right top;
    color: #00a; /* just to make it easy to know which class it has */
}

要在加载页面时隐藏所有子元素。。。

$('#tree > li').addClass('closed');
// hide the level 2 ul's
$('#tree > li ul').hide();

然后在您的点击处理程序中:

$("#tree > li > span").click(function (event) {
    event.preventDefault();
    // swap the opened and closed classes
    $(this).parent().toggleClass('opened closed');
     // toggle the level 2 ul instead of li
    $(this).parent().find("ul").toggle();
});

在此处进行演示:http://jsfiddle.net/cTLGN/


附加:

这个演示代码没有使用缓存对jQuery对象的引用来使其更易于阅读。在现实中而不是做:

$(this).parent().toggleClass('opened closed');
$(this).parent().find("ul").toggle();

应该这样做:

var parent = $(this).parent(); // search the DOM once for this' parent, and remember it
parent.toggleClass('opened closed');
parent.find("ul").toggle();

因为每次使用jQuery的$((构造函数时,都需要搜索整个DOM,如果重复使用,这可能会非常昂贵。