addEventListener()到不存在的元素? [英] addEventListener() to non-existent elements?

查看:94
本文介绍了addEventListener()到不存在的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在元素上附加了 click 事件监听器

  document.querySelector('。class-name')。addEventListener('click',function(){

});

该元素可能会或可能不会从服务器端生成。



因此,如果服务器生成了该元素,则所有工作正常,但如果没有,那么我将收到如下错误:



无法读取null的属性'addEventListener'



我知道为什么会发生这种情况,但是我想知道是否有更好的附加方法

解决方案

没有某种条件的测试是无法做到的,但是与 if 块相比,您可以节省一些字符,因此:

  var el = document.querySelector('。class-name'); 
el&& el.addEventListener(...);

我不认为有任何简单的方法可以避免使用临时变量(但请参见下文)。 / p>




NB:包含以下内容只是为了表明它是可能的,不应被视为建议;-)



如果这是HTML和JS中非常常见的模式,一种避免临时分配给 el 的方法是这样的:

  var丢失= {
addEventListener:function(){};
}; //一个空元素

(document.querySelector(’。className’)||丢失).addEventListener(...);

这个想法是 ||丢失确保存在某些东西来吸收 addEventListener 引用和调用。


I have attached a click event listener on an element like:

document.querySelector('.class-name').addEventListener('click', function () {

});

The element may or may not get generated from the server-side.

So, if the server generates the element then all works fine but if not then i get a error like:

Cannot read property 'addEventListener' of null

I know why this happens, but I want to know whether there is any better way to attach event listeners to elements which won't generate such errors?

解决方案

There's no way of doing this without some sort of conditional test, but you can save a few characters compared to an if block thus:

var el = document.querySelector('.class-name');
el && el.addEventListener(...);

I don't believe there's any simple way of avoiding the temporary variable (but see below).


NB: the below is included just to show that it's possible and should not be construed as a recommendation ;-)

If this is a very common pattern in your HTML and JS, a way to avoid the temporary assignment to el is this:

var missing = {
  addEventListener: function() {};
};  // a "null" element

(document.querySelector('.className') || missing).addEventListener(...);

The idea being that the || missing ensures that there's something present to absorb the addEventListener reference and invocation.

这篇关于addEventListener()到不存在的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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