jquery显示列表项

jquery display list items

本文关键字:列表 显示 jquery      更新时间:2023-09-26

我有两个或多个无序列表,每个列表中的第一个列表项可见,其他列表项隐藏。

当点击第一个列表itme时,它应该显示下面的所有其他li,并隐藏在另一个ul中打开的任何其他li。

我似乎无法使它正确显示。

我无法更改示例中的类名,因为它们是在核心代码内部生成的,并用于其他元素。

谢谢你的帮助。

http://jsfiddle.net/ukkpower/En7KV/4/

试试这个:

$('ul').on('click','.maincat',
           function(e){
               // prevents the default click action of the a element
               e.preventDefault();
               // finds the sibling elements, and shows them if hidden,
               // hides them if visible
               $(this).siblings().toggle();
               // finds the closest ul ancestor of the clicked element
               // finds the other ul siblings of that ancestor-ul
               // finds the '.maincat' class element's siblings that are visible
               // hides those visible elements
              $(this)
                 .closest('ul')
                 .siblings('ul')
                 .find('.maincat')
                 .siblings('li:visible')
                 .hide();
           });

JS Fiddle演示。


编辑以添加参考文献(如下)和此注释:

请注意,从jQuery 1.7开始,live()方法已被弃用(因此,可能会或更可能会放弃对的支持)。对于jQuery 1.7+,请使用on()方法(请参阅以下参考文献),在1.7之前,建议优先使用delegate()方法。

本说明的参考资料是live()的API文档,请参阅参考资料。

请注意

参考文献:

  • closest()
  • delegate()
  • e.preventDefault()
  • find()
  • hide()
  • CCD_ 10
  • CCD_ 11
  • siblings()
  • toggle()