无法读取 null 的属性“addEventListener" [英] Cannot read property 'addEventListener' of null

查看:58
本文介绍了无法读取 null 的属性“addEventListener"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在一个项目中使用 vanilla JavaScript.我有几个功能,其中之一是打开菜单的按钮.它适用于目标 id 存在的页面,但在 id 不存在的页面上会导致错误.在函数找不到 id 的那些页面上,我收到无法读取 null 属性 'addEventListener'"错误,并且我的其他函数都不起作用.

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;
};

我该如何处理?我可能需要将此代码全部包装在另一个函数中或使用 if/else 语句,以便它仅搜索特定页面上的 id,但不确定是否准确.

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.

推荐答案

我认为最简单的方法是在添加事件侦听器之前检查 el 是否为空:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆