0
下文提到的是導航菜單我的HTML代碼:在單擊JS不工作
<nav role="navigation" class="nav">
<ul class="nav-items">
<li class="nav-item">
<a href="#" class="nav-link"><span>About Us</span></a>
</li>
<li class="nav-item dropdown">
<a href="#" class="nav-link"><span>Divisions</span></a>
<nav class="submenu">
<ul class="submenu-items">
<li class="submenu-item"><a href="#" class="submenu-link">Div 1</a></li>
<li class="submenu-item"><a href="#" class="submenu-link">Div 2</a></li>
</ul>
</nav>
</ul>
</nav>
我的JavaScript代碼如下:
$(document).ready(function() {
[].slice.call(document.querySelectorAll('.dropdown .nav-link'))
.forEach(function(el) {
el.addEventListener('click', onClick, false);
});
function onClick(e){
e.preventDefault();
var el = this.parentNode;
el.classList.contains('show-submenu') ? hideSubMenu(el) : showSubMenu(el);
}
function showSubMenu(el){
el.classList.add('show-submenu');
document.addEventListener('click', function onDocClick(e){
e.preventDefault();
if(el.contains(e.target)){
return;
}
document.removeEventListener('click', onDocClick);
hideSubMenu(el);
});
}
function hideSubMenu(el){
el.classList.remove('show-submenu');
}
});
而且現在上單擊操作不管用。有人請幫助!我從一些在線教程中獲得了這些代碼。由於我是JavaScript新手,請更正我的代碼。先謝謝你。
你在控制檯中看到任何錯誤? – Saurabh
您是否將jquery加載到您網頁的標籤? –