【发布时间】:2018-06-18 14:25:59
【问题描述】:
我使用 google MATERIAL COMPONENTS FOR THE WEB,但“简单菜单”出现问题。检查我的代码笔:[每页有多个菜单?][1]
[1]: https://codepen.io/QJan84/pen/govRmg
第一个菜单有效,其他菜单无效。 每页有多个菜单需要做什么?
【问题讨论】:
标签: web material-components material-components-web
我使用 google MATERIAL COMPONENTS FOR THE WEB,但“简单菜单”出现问题。检查我的代码笔:[每页有多个菜单?][1]
[1]: https://codepen.io/QJan84/pen/govRmg
第一个菜单有效,其他菜单无效。 每页有多个菜单需要做什么?
【问题讨论】:
标签: web material-components material-components-web
您将document.querySelector 用于菜单和切换,但它只会返回分别匹配“.mdc-simple-menu”和“.js--toggle-dropdown”的第一个节点元素。
相反,您应该使用 document.querySelectorAll,它将返回 NodeList,您需要将其返回到 convert to array to iterate with its elements。
我将您的示例菜单和开关包装到容器中,以便使用 Node.parentElement 更轻松地选择开关。
所以,最终的结果可能是这样的:
const menuEls = Array.from(document.querySelectorAll('.mdc-simple-menu'));
menuEls.forEach((menuEl) => {
// Initialize MDCSimpleMenu on each ".mdc-simple-menu"
const menu = new mdc.menu.MDCSimpleMenu(menuEl);
// We wrapped menu and toggle into containers for easier selecting the toggles
const dropdownToggle = menuEl.parentElement.querySelector('.js--dropdown-toggle');
dropdownToggle.addEventListener('click', () => {
menu.open = !menu.open;
});
});
【讨论】: