2017-10-17 71 views
-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); 
} 
}); 
+3

你并不需要指定''调用'getElementById'时。 –

回答

1

我认为你需要从“礼”列表循环每一个项目,因为你得到所有“礼”可用:

let menuItems = menu.getElementsByTagName('li'); 

for(let menuItem of menuItems) { 
    ... 
};