无法读取null的属性'addEventListener' [英] Cannot read property 'addEventListener' of null
问题描述
我必须为项目使用vanilla JavaScript。我有几个功能,其中一个是打开菜单的按钮。它在存在目标标识的页面上工作,但在id不存在的页面上导致错误。在那些功能找不到id的页面上,我收到了Can not read property'addEventListener'of null错误,并且我的其他功能都没有工作。
打开菜单的按钮的代码。
函数swapper(){
toggleClass(document.getElementById('overlay'),'open');
}
var el = document.getElementById('overlayBtn');
el.addEventListener('click',swapper,false);
var text = document.getElementById('overlayBtn');
text.onclick = function(){
this.innerHTML =(this.innerHTML ===Menu)? 关闭:菜单;
返回false;
};
我该如何处理?我可能需要将这些代码包装在另一个函数中,或者使用if / else语句,以便它只在特定页面上搜索id,但不能确定。我认为最简单的方法是检查 el
在添加事件侦听器之前,它不为null:
var el = document.getElementById('overlayBtn');
if(el){
el.addEventListener('click',swapper,false);
}
I have to use vanilla JavaScript for a project. I have a few functions, one of which is a button that opens a menu. It works on pages where the target id exists, but causes an error on pages where the id doesn't exist. On those pages where the function cannot find the id, I receive a "Cannot read property 'addEventListener' of null " error and none of my other functions work.
Below is the code for the button that opens the menu.
function swapper() {
toggleClass(document.getElementById('overlay'), 'open');
}
var el = document.getElementById('overlayBtn');
el.addEventListener('click', swapper, false);
var text = document.getElementById('overlayBtn');
text.onclick = function(){
this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
return false;
};
How do I deal with this? I probably need to all wrap this code in another function or use an if/else statement so that it only searches for the id on specific pages, but not sure exactly.
I think the easiest approach would be to just check that el
is not null before adding an event listener:
var el = document.getElementById('overlayBtn');
if(el){
el.addEventListener('click', swapper, false);
}
这篇关于无法读取null的属性'addEventListener'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!