我有多级菜单如下:
<li><a id="Default" href="Default.aspx">Dashboard</a></li>
<li><a id="Readings" href="#">Readings<span class="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a id="Reading-Dip" href="Readings.aspx?Mode=Dip">Dip</a></li>
<li><a id="Reading-Dispenser" href="Readings.aspx?Mode=Dispenser">Dispenser</a></li>
</ul>
</li>
<li><a id="Transactions" href="#"></i>Transactions<spanclass="fa arrow"></span></a>
<ul class="nav nav-second-level">
<li><a id="Transactions-1" href="Transactions.aspx?1">Second Level Link</a </li>
<li><a id="Transactions-2" href="Transactions.aspx?2">Second Level Link</a> </li>
<li><a id="Transactions-3" href="Transactions.aspx?3">Second Level Link<span class="fa arrow"></span></a>
<ul class="nav nav-third-level">
<li><a id="Transactions-3-1" href="Transactions.aspx?3-1">Third Level Link</a> </li>
<li><a id="Transactions-3-2" href="Transactions.aspx?3-2">Third Level Link</a> </li>
<li><a id="Transactions-3-3" href="Transactions.aspx?3-3">Third Level Link</a> </li>
</ul>
</li>
</ul>
</li>
如果匹配网址,我需要在active-menu
上设置li
课程。它对于单击的li
工作正常。在多级ul
的情况下,我还需要设置父级别。
这是我写的当前jQuery函数:
var url = window.location;
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active-menu');
示例:如果我选择Transactions-3-1,那么我需要在以下所有元素上设置active
类:
答案 0 :(得分:2)
您可以使用parents([selector])
查找与选择器匹配的所有元素的祖先,在您的情况下,您可以使用以下匹配所有li
祖先:
var url = window.location;
$('ul.nav a').filter(function () {
return this.href == url;
}).parents('li').addClass('active-menu');