如果我有
var btn = document.getElementsByClassName('top_button')[0];
btn.addEventListener('click', function() { /* some here */ }));
和 undefined 类我得到一个 TypeError
。我想知道逃避这种情况的通常方法是什么。会不会是
var btn = document.getElementsByClassName('top_button')[0] || {};
还是我应该采取不同的做法? jQuery 是如何做到这一点的,因为当我使用 $('.top_button')
并且该元素不存在时,它只返回一个对象。
谢谢
最佳答案
如果您真的只想要第一个,那么我同意 Praveen 的观点,即 if
是最清晰、最简单的解决方案,尽管我通常在不同的地方这样做:
var btn = document.getElementsByClassName('top_button')[0];
if (btn) {
btn.addEventListener('click', function() { /* some here */ }));
}
getElementsByClassName
返回的集合可靠,跨浏览器,给你undefined
如果您要求的索引处没有元素(就像 JavaScript 数组一样)。
但我会使用 querySelector
而不是 getElementsByClassName
,因为您只想要第一个而无需构建列表,并且 querySelector
在所有现代浏览器和 IE8 上都有(而 IE8 缺少 getElementsByClassName
)。
var btn = document.querySelector('.top_button');
if (btn) {
btn.addEventListener('click', function() { /* some here */ }));
}
querySelector
接受任何 CSS 选择器(包括复杂的选择器)并返回第一个匹配元素,或 null
.它的表弟querySelectorAll
返回一个列表(如果没有匹配则可以为空)。
如果您想在所有 匹配元素上 Hook 事件,Quentin has you covered .
How is jQuery doing this, because when I'm using $('.top_button') and the element is not there, it just returns an object.
jQuery 对象是 DOM 元素集的包装器(通常,它们可以是其他东西的包装器,但在典型使用中它们是 DOM 元素)。所以当你做 $('.top_button')
,你会得到一个 jQuery 对象,它是一个没有任何内容的集合的包装器。您可以调用该 jQuery 对象,例如 .on
,并且它们不会失败(因为 jQuery 对象存在),但它们也不会做任何事情(因为集合中没有元素可以用来做任何事情)。
我不是建议这样做,但您可以自己用 querySelectorAll
做同样的事情. (jQuery 比 querySelectorAll
早了几年,最初 John Resig 为它构建了一个完整的选择器引擎。现代浏览器在类似 jQuery 的东西中不需要这样做,除非你想添加自己的 CSS 选择器,比如 jQuery 的 :has
。)
只是通过说明 jQuery 正在做什么(纯粹是概念上的):
function DomQuery(selector) {
// Get the matching elements, as an array (the `slice` thing turns
// the collection returned by `querySelectorAll` into an array)
this.elements = Array.prototype.slice.call(document.querySelector(selector));
}
DomQuery.prototype.on = function(eventName, handler) {
this.elements.forEach(function(element) {
element.addEventListener(eventName, handler, false);
});
return this;
};
用法:
new DomQuery(".top_button").on("click", function() {
// do something
});
我们可以通过制作 new
使其更像 jQuery可选:
function domQuery(selector) {
// If not called via `new`, do that
if (!(this instanceof domQuery)) {
return new domQuery(selector);
}
// Get the matching elements, as an array (the `slice` thing turns
// the collection returned by `querySelectorAll` into an array)
this.elements = Array.prototype.slice.call(document.querySelector(selector));
}
domQuery.prototype.on = function(eventName, handler) {
this.elements.forEach(function(element) {
element.addEventListener(eventName, handler, false);
});
return this;
};
用法:
domQuery(".top_button").on("click", function() {
// do something
});
关于javascript - 转义不存在的元素的常用方法是什么(就像 jQuery 那样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34268299/