jQuery:仅选择 ul,而不选择 ul ul
我正在尝试使用 jQuery 提交一个基本的手风琴样式菜单。
这是菜单:
这是一段代码,给它手风琴功能:
$('#access ul li').click(function(){
$('#access ul ul:visible').slideUp();
$(this).children('ul:hidden').slideDown();
});
问题:单击子菜单链接会使子菜单向上滑动(并关闭)。
我想在单击子菜单链接并向上滑动时保持子菜单打开仅有的当点击顶级链接时。
如何使用 jQuery 仅选择顶级 ul 来为子菜单设置动画?或者有没有办法选择子菜单链接并“告诉它”以在单击时保持子菜单打开?
我会欣赏你的智慧!
I'm trying to beat a basic accordion style menu into submission – using jQuery.
Here's the menu:
Here's a snippet of code that gives it accordion functionality:
$('#access ul li').click(function(){
$('#access ul ul:visible').slideUp();
$(this).children('ul:hidden').slideDown();
});
The problem: a click on a sub-menu link makes the submenu slide up (and close).
I want to keep the submenu open when the submenu link is clicked, and slide up only when a top level links are clicked.
How can I select only the top level ul with jQuery to animate the submenu? Or is there a way to select the sub-menu link and "tell it" to keep the submenu open on click?
I would appreciate your wisdom!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来你需要在 CSS 中使用
>
运算符。<代码>.foo> .bar 选择类
bar
的所有元素,该元素是类foo
的元素的直接子元素明白了,工作代码:
防止菜单滑回再次起来,这有效:
It seems like you need to use the
>
operator in CSS..foo > .bar
selects all elements with classbar
that is a direct child of an element with classfoo
Got it, working code:
To keep the menu from sliding back up again this works:
您无法阻止菜单关闭,因为当您单击链接时,浏览器正在发出新请求并重新加载菜单。只需观看 URL 栏即可。当您单击子菜单链接时,URL 会发生变化。
您需要在 URL 中添加一些内容以阻止子菜单折叠,或者测试 URL 以查看页面加载后是否应重新打开折叠面板。
You can't stop the menu from closing because the browser is making a new request and loading the menu fresh when you click on the links. Just watch the URL bar. When you click the sub-menu links, the URL changes.
You'll need to add something to the URL to stop the sub-menu from collapsing, or test the URL to see if it should re-open the accordion after the page loads.
这更简单并且对我有用。
This is much simpler and works for me.
我花了 10 分钟来阅读和理解你的代码,因为你有很多样式和 id,这使得它变得非常复杂,请注意最佳实践,
你所需要的就是类似的东西
i have took 10 minutes to read and understand your code because you have a lot of styles and id's and this is complicating it a lot, take care of the best practices
All you need is something like