我有一个问题,我有一个菜单与父菜单项,如果有一个子菜单上点击它切换嵌套的ul。
现在,我有2个,问题是当我把它放在foreach中时,它会切换这两个子菜单,而不是当前单击的父项子菜单。
我怎样才能告诉JS只从单击的元素切换div?
- 在WordPress中的PHP:**
<?php
function main_navigation() {
$menu_name = 'main_menu';
$locations = get_nav_menu_locations();
$menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
$menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'order' => 'ASC' ) );
$count = 0;
$sub_menu = false;
?>
<ul class="header__list">
<?php
foreach( $menu_items as $item ):
$link = $item->url;
$title = $item->title;
$class = $item->classes[0];
// item does not have a parent so menu_item_parent equals 0 (false)
if ( !$item->menu_item_parent ):
// save this id for later comparison with sub-menu items
$parent_id = $item->ID;
?>
<li class="header__item">
<a href="<?php echo $link; ?>" class="header__link <?php echo $class ?>"><?php echo $title; ?></a>
<?php endif; ?>
<?php if ( $parent_id == $item->menu_item_parent ): ?>
<?php if ( !$sub_menu ): $sub_menu = true; ?>
<ul class="header__sub-list" aria-role="header-sublist">
<?php endif; ?>
<li class="header__sub-item">
<a href="<?php echo $link; ?>" class="header__sub-link"><?php echo $title; ?></a>
</li>
<?php if ( $menu_items[ $count + 1 ]->menu_item_parent != $parent_id && $sub_menu ): ?>
</ul>
<?php $sub_menu = false; endif; ?>
<?php endif; ?>
</li>
<?php
$count++;
endforeach;
?>
</ul>
<?php
}
- 联属萨摩亚**
const headerSubLists = document.querySelectorAll('.header__link-sub');
headerSubLists.forEach((headerSubList) => {
const headerSubMenu = document.querySelectorAll(
'[aria-role="header-sublist"]'
);
const openSubMenu = (e) => {
e.preventDefault();
headerSubMenu.forEach((menu) => {
menu.classList.toggle('is-open');
});
};
headerSubList.addEventListener('click', openSubMenu);
});
1条答案
按热度按时间byqmnocz1#
首先像这样修改你的js:
然后在php文件中创建子菜单时将data属性添加到父项中: