简体   繁体   English

使用javascript设置活动类进行导航

[英]Setting active class for navigation using javascript

I am using PHP to echo my list of navigation options, this is being done due to different privileges for each user. 我正在使用PHP来回显我的导航选项列表,由于每个用户的权限不同,因此无法完成。 The list is divided into groups which has a few more list items, one a user clicks on the heading of the group expands, listing the sub-menu. 该列表分为几组,其中还有更多的列表项,用户单击该组的标题会展开一个列表,列出子菜单。 I have been able to set the active class for the menu which is currently open using this piece of javascript: 我已经能够使用该段javascript设置当前打开的菜单的活动类:

function initMenu() {
    $('#menu ul').hide();
    $('#menu li a').click(function() {
        var checkElement = $(this).next();
        if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        //slide up if visible (works fine).
        }
        if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        //otherwise slideDown (works fine too).
        }
    });
}

$(document).ready(function() {markActiveLink();initMenu();});

function markActiveLink() {
   $("#menu li ul li a").filter(function() {
       return $(this).prop("href").toUpperCase() == window.location.href.toUpperCase();
   }).addClass("active")
   .closest('ul') //some markup problem
   .slideDown('normal');
}

And this is my markup for list that are being displayed: 这是我正在显示的列表的标记:

echo "<ul id='menu'>";
 echo "<li><a href='#'>Adminstration</a>
<ul><li>";
echo "<a href='path_to_page/usermanagement.php'>User Management</a>";
echo "</li><li>";
// and some more items

Here administration is my group heading and User Management is my sub-group. 在这里,管理是我的小组标题,而用户管理是我的子小组。 Now using the above piece of code i am still not able to expand my menu on different pages, so that the user knows which page he is on? 现在,使用上面的代码,我仍然无法在不同页面上展开菜单,以便用户知道他在哪个页面上?

I figured out the problem, for some odd reason, it requires me to declare the variable first: 我发现了这个问题,出于某种奇怪的原因,它要求我首先声明该变量:

 var checkEle = $("#menu li ul li a").filter(function() {
       return $(this).prop("href").toUpperCase() == window.location.href.toUpperCase();
   }).addClass("active")
   .closest('ul');   //get the closest ul 
   console.log(checkEle);
   checkEle.slideDown('normal');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM