【问题标题】:Best approach to handle "Cannot read property 'addEventListener' of null" errors处理“无法读取属性‘addEventListener’ of null”错误的最佳方法
【发布时间】:2018-05-30 10:37:36
【问题描述】:

目前我所做的是检查页面中是否存在元素,但因此我的代码有很多 if 条件。当元素不存在时,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);
}
....
...

【问题讨论】:

    标签: javascript jquery event-handling dom-events


    【解决方案1】:

    jquery 如何处理...?

    jQuery 的 API 是基于集合的,而不是基于元素的。 DOM 的 API 是基于元素的。当您在 jQuery 中执行 $("#foo").on("click", ...) 时,如果没有带有 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

    【讨论】:

    • 美丽的@T.J.
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2020-09-04
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多