我试图找到链接的父元素,当它具有特定的类名时。
我有以下列表,我用作导航菜单,当我加载页面时,li(has-subitem)里面的ul(子项)关闭(显示:隐藏)。现在我想根据我所在的页面打开其中一个。
为此,我试图这样做。
每当我在“subitem li”里面有一个类名为“current”的链接时,我想保持“has-subitem”打开而不是关闭它。 fiddle这里
但它不能以某种方式工作。我是JS的新手:(
<ul class="navi-list">
<li class="no-subitem"> <a class="current">Overview</a>
<span class="navi-current"></span>
</li>
<li><a class="has-subitem"><i class="fa fa-caret-right fw"> </i> Policies & Procedures </a>
<ul class="submenu">
<!-- whenever I have this "current" i would like to find the li above with class "has-subitem" containing this link---->
<li><a class="current" href="#"> Documents & Resources </a>
</li>
<li><a href="#"> Upcoming Events </a>
</li>
<li><a href="#"> News </a>
</li>
<li><a href="#"> Announcements </a>
</li>
</ul>
</li>
<li><a class="has-subitem"><i class="fa fa-caret-right fw"> </i> Feeds & Discussions </a>
<ul class="submenu">
<li><a href="#"> Blog & Podcasts </a>
</li>
<li><a href="#"> Photos & Videos </a>
</li>
</ul>
</li>
<li><a class="has-subitem"><i class="fa fa-caret-right fw"> </i> About Us </a>
<ul class="submenu">
<li><a href="#"> FAQs </a>
</li>
<li><a href="#"> Contact Us </a>
</li>
</ul>
</li>
</ul>
答案 0 :(得分:2)
您可以忽略.has-subitem.current
隐藏命令中的submenu
元素,如
$(".has-subitem:not(.current)").next(".submenu").hide();
$('.navi-list a.current').closest('li:has(> a.has-subitem)').children('.submenu').show();
$(document).on("click", ".has-subitem", function() {
$(this).next(".submenu").slideToggle();
$(this).find('i').toggleClass("fa-caret-right fa-caret-down");
});
&#13;
<link rel="stylesheet" type="text/css" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="navi-list">
<li class="no-subitem">
<a class="">Overview</a>
<span class="navi-current"></span>
</li>
<li>
<a class="has-subitem"><i class="fa fa-caret-right fw"> </i> Policies & Procedures </a>
<ul class="submenu">
<li><a href="#" class="current"> Documents & Resources </a></li>
<li><a href="#"> Upcoming Events </a></li>
<li><a href="#"> News </a></li>
<li><a href="#"> Announcements </a></li>
</ul>
</li>
<li>
<a class="has-subitem"><i class="fa fa-caret-right fw"> </i> Feeds & Discussions </a>
<ul class="submenu">
<li><a href="#"> Blog & Podcasts </a></li>
<li><a href="#"> Photos & Videos </a></li>
</ul>
</li>
<li>
<a class="has-subitem"><i class="fa fa-caret-right fw"> </i> About Us </a>
<ul class="submenu">
<li><a href="#"> FAQs </a></li>
<li><a href="#"> Contact Us </a></li>
</ul>
</li>
</ul>
&#13;