简体   繁体   中英

dropdown menu on click with jquery

I've been working with this thread . But I don't have the rep to ask them the question.

I have this setup in a Wordpress install using the default menu hierarchy that Wordpress spits out, like this:

HTML:

<div class="menu-featured-categories-container">
<ul id="menu-featured-categories">
    <li class="menu-item-has-children">
      <a href="#">Featured Categories</a>
        <ul class="sub-menu">
            <li>...</li>
            <li>...</li>
            <li>...</li>
        </ul>
    </li>
</ul>
</div>

CSS:

#menu-featured-categories ul.sub-menu {
    display: none;
}

#menu-featured-categories ul.visible {
    display: block;
}

jQuery:

$(document).ready(function() {
    $('.menu-item-has-children').click(function() {
        $('.sub-menu').toggleClass('visible');
    });
});

It's just not working for me. So my question is: What am I doing wrong? Any thoughts would be greatly appreciated. Thanks.

In many cases, you need to use noConflict mode to write your jQuery in Wordpress. Alternatively, you can use 'jQuery' instead of $ in all instances.

So here are your options, either replace the wrapping

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

with

jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});

Your second option is to rewrite your code as follows:

jQuery(document).ready(function() {
    jQuery('.menu-item-has-children').click(function() {
        jQuery('.sub-menu').toggleClass('visible');
    });
});

Either of these should resolve your issue, considering that the code works, which it seemingly does based on Zakaria's Fiddle in the comments.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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