gpt4 book ai didi

javascript - 处理 "Cannot read property ' addEventListener' of null"错误的最佳方法

转载 作者:行者123 更新时间:2023-11-28 13:00:55 25 4
gpt4 key购买 nike

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

最佳答案

How jquery handles that...?

jQuery 的 API 是基于集合的,而不是基于元素的。 DOM 的 API 是基于元素的。当您在 jQuery 中执行 $("#foo").on("click", ...) 时,如果没有带有 id 的元素 "foo “$() 返回一个空集,而不是 null,并对其调用 on set 不执行任何操作,但也不会导致错误。

由于 getElementById 返回 elementnull,因此您必须进行已显示的检查,以防止尝试调用 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

关于javascript - 处理 "Cannot read property ' addEventListener' of null"错误的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50602547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com