2017-10-17 90 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) { 
    ... 
};