我想制作一个手风琴,单击该子菜单项时它会展开。我的问题是每次我扩展子菜单时,菜单项都会一直切换。它会切换子菜单,但是我必须再次展开菜单才能看到它。
这是我的HTML:
<div class="fs_menu_overlay"></div>
<div class="hamburger_menu">
<div class="hamburger_close"><i class="fa fa-times" aria-hidden="true"></i></div>
<div class="hamburger_menu_content text-right">
<ul class="menu_top_nav">
<li class="menu_item has-children">
<a href="#" class="anchor-head">
<!-- Populated by javascript -->
</a>
<ul class="menu_selection">
<!-- Populated by javascript -->
</ul>
</li>
<li class="menu_item"><a href="#">Home</a></li>
<li class="menu_item has-children">
<a href="#clothing" class="submenu" data-toggle="collapse">CLOTHING <i class="fa fa-angle-down"></i></a>
<ul id="clothing" class="menu_selection">
<li class="submenu_item has-subchildren"><a href="#menclothing" data-toggle="collapse">MEN'S CLOTHING <i class="fa fa-angle-down"></i></a>
<ul id="menclothing" class="menu_selection">
<li><a href="#">TSHIRTS</a></li>
<li><a href="#">POLO SHIRTS</a></li>
<li><a href="#">JACKETS</a></li>
</ul>
</li>
<li class="submenu_item has-subchildren"><a href="#womenclothing" data-toggle="collapse">WOMEN'S CLOTHING <i class="fa fa-angle-down"></i></a>
<ul id="womenclothing" class="menu_selection">
<li><a href="#">DRESSES</a></li>
<li><a href="#">SKIRTS</a></li>
<li><a href="#">TOPS</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
这是我的Jquery:
if($('.menu_item').length)
{
var items = document.getElementsByClassName('menu_item');
var i;
for(i = 0; i < items.length; i++)
{
if(items[i].classList.contains("has-children"))
{
items[i].onclick = function()
{
this.classList.toggle("active");
var panel = this.children[1];
if(panel.style.maxHeight)
{
panel.style.maxHeight = null;
}
else
{
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}
}
}
if($('.submenu_item').length)
{
var subitems = document.getElementsByClassName('submenu_item');
var i;
for(i = 0; i < subitems.length; i++)
{
if(subitems[i].classList.contains("has-subchildren"))
{
subitems[i].onclick = function()
{
this.classList.toggle("active");
var panel = this.children[1];
if(panel.style.maxHeight)
{
panel.style.maxHeight = null;
}
else
{
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}
}
}
我不想使用插件,因为它可能会影响带有注释Populated by Javascript
的HTML。
答案 0 :(得分:0)
当您单击“ .submenu_item”时,该事件也会冒泡到父元素。这意味着“ .menu_item”也将收到点击事件。您应该尝试在'.submenu_item'上使用stopPropagation()https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation