Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

html - jquery to toggle sub-menu but keep sub-menu open if sub-menu page active

Just trying to dive into jquery and forgive me if this has already been answered. Searched but couldn't find an example relevant to what I'm trying to do.

I have a vertical menu with some sub menus. It is working that when the top level menu is clicked the sub menu opens up. The problem is that I would like the sub menu to stay open when one of sub-menu items is clicked. As it is now, when a sub-menu item is clicked the menu collapses.

Here is my code:

// Add class of drop if item has sub-menu
$('ul.sub-menu').closest('li').addClass('drop');

// Left Sidebar Main Navigation
var menu_ul = $('.menu > li.drop > ul'),
    menu_a  = $('.menu > li.drop > a');

menu_ul.hide();

menu_a.click(function(e) {
    e.preventDefault();
    if(!$(this).hasClass('active')) {
        menu_a.removeClass('active');
        menu_ul.filter(':visible').slideUp('normal');
        $(this).addClass('active').next().stop(true,true).slideDown('normal');
    } else {
        $(this).removeClass('active');
        $(this).next().stop(true,true).slideUp('normal');
    }
});

I think if I try and translate what I want into a clear coder type sentence it would read like this. Basically I need to query the DOM for any active menu that has sub-menu, and if the page is showing one of the submenu items, then display the sub-menu dropdown.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you have two options.

  1. Consider using Ajax to load your pages
  2. Simulate the click event on each page.

For example:

For "Portfolio" items add this

<script type="text/javascript">
  $(document).ready(function(){
      jQuery('#menu-item-38>a').trigger('click');
  });
</script>

For "About Us":

<script type="text/javascript">
  $(document).ready(function(){
      jQuery('#menu-item-180>a').trigger('click');
  });
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...