繁体   English   中英

处理“Cannot read property 'addEventListener' of null”错误的最佳方法

[英]Best approach to handle “Cannot read property 'addEventListener' of null” errors

目前我所做的是检查页面中是否存在元素,但我的代码因此有很多条件。 当元素不存在时,Jquery 事件侦听器不会显示错误。 jQuery 如何处理这个问题以及我可以使用哪些技术来进行更好的设计?

var el = document.getElementById('el');
var another_el = document.getElementById('another_el');

if(another_el){
el.addEventListener('click', swapper, false);
}

if(el){
  el.addEventListener('click', swapper, false);
}
....
...

jquery 如何处理...?

jQuery 的 API 是基于集合的,而不是基于元素的。 DOM 的 API 是基于元素的。 当你这样做$("#foo").on("click", ...) jQuery中,如果有与没有元素id "foo"$()返回一个空集,不null ,并呼吁on上该集合不执行任何操作,但也不会导致错误。

由于getElementById返回一个元素null ,您必须进行检查以防止尝试在null上调用方法,这会导致错误。

如果您想在不使用 jQuery 的情况下获得基于集合的 API 的好处,您可以编写自己的实用函数集,这些函数使用querySelectorAll为自己提供一个围绕 DOM API 的基于集合的瘦包装器,如果您愿意的话。

这是一个非常简单的入门示例:

 // The object we use as the prototype of objects returned by `domSet` var domSetMethods = { on: function(eventName, handler) { // Loop through the elements in this set, adding the handler this.elements.forEach(function(element) { element.addEventListener(eventName, handler); }); // To support chaining, return `this` return this; } }; // Get a "DOM set" for the given selector function domSet(selector) { // Create the set, usign `domSetMethods` as its prototype var set = Object.create(domSetMethods); // Add the elements set.elements = Array.prototype.slice.call(document.querySelectorAll(selector)); // Return it return set; } domSet("#foo").on("click", function() { console.log("foo clicked"); }); // Notice that even though there's no id="bar" element, we don't get an error domSet("#bar").on("click", function() { console.log("bar clicked"); });
 <div id="foo">foo element (there is no bar element)</div>

您可以向domSetMethods添加方法以执行其他操作。 为了支持 jQuery 提供的 API 链式风格,在大多数情况下,您会从这些方法中返回this

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM