-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'时。 –