简体   繁体   中英

jQuery onclick ul li i and display children ul if exists

I am trying to make a custom mobile menu. The idea is when user clicks on the chevron-right it will slideToggle the children UL and add class to the current LI ( active ) as well as it will display: block "chevron-down" and display: none "chevron-right". In other words the arrow will be changed from right to down.

    jQuery(function(){

  jQuery("#menu-main-menu-m li i.fa-chevron").click(function() {
    if(jQuery(this).closest("li").children("ul").length) {
    jQuery(this).toggleClass('active');
    jQuery(this).children('ul').slideToggle(500);

}
else {

}
  });

});

Here is the HTML

<ul id="menu-main-menu-m" class="menu"><li id="menu-item-3" class="menu-item-has-children menu-item-3 menu-item-ancestor"><a href="#">Open Account</a><i class="fa fa-chevron-right"></i><i class="fa fa-chevron-down"></i><ul class="sub-menu"><li>....</li><li></li></ul>

I think this is what you are looking for:

 $("#menu-main-menu-m i[class*='fa-chevron']").click(function() {
    if($(this).closest("li").children("ul").length) {
      $(this).text($(this).text() == "Right" ? "Down" : "Right");
    $(this).closest("li").children("ul").toggleClass('active');
    $(this).closest("li").children("ul").slideToggle(500);
   }
  });

http://jsfiddle.net/rzseLj27/2/

Basic idea using CSS and binding the click event to the elements.

 jQuery(function() { jQuery("#menu-main-menu-m").on("click", "li i.fa", function() { console.log("here"); var li = $(this).closest("li"); li.toggleClass("active"); li.find(".sub-menu").slideToggle(); }); }); 
 .menu li i { display: inline-block; cursor: pointer; } .menu li.active i { display: none; } .menu li i + i { display: none; } .menu li.active i + i { display: inline-block; } .sub-menu { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css"> <ul id="menu-main-menu-m" class="menu"> <li id="menu-item-3" class="menu-item-has-children menu-item-3 menu-item-ancestor"><a href="#">Open Account</a><i class="fa fa-chevron-right"></i><i class="fa fa-chevron-down"></i> <ul class="sub-menu"> <li>....</li> <li></li> </ul> </li> </ul> 

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