-1
我在jQuery中有簡單的菜單腳本。我想重構純JavaScript代碼。目的是最大化性能。但我有錯誤「無法讀取屬性'addEventListener'或null」。我究竟做錯了什麼?jQuery到Javascript的麻煩
的jQuery:
$('#menu li').on('touchstart click', function (e) {
e.preventDefault();
var item = $(this);
var submenu = item.find('ul');
// Display submenu, if there is one
// Otherwise follow the link
if (submenu.length > 0) {
submenu.addClass('open');
return;
} else {
var link = item.find('a');
window.location = link.attr('href');
}
});
的JavaScript:
let menu = document.getElementById('#menu');
let menuItem = menu.getElementsByTagName('li');
menuItem.addEventListener("click", function (e) {
e.preventDefault();
let submenu = this.find('ul');
// Display submenu, if there is one
// Otherwise follow the link
if (submenu.length > 0) {
submenu.classList.add("open");
return;
} else {
let link = this.find('a');
window.location.replace(href);
}
});
你並不需要指定''調用'getElementById'時。 –