这两种引用方法的主要区别是什么?
使用它们的好处有哪些?此外,它们分别最适合哪种使用情况?
var selection = document.querySelector('.selector') !== null;
var selection = document.querySelector('.selector');
前者是否仅为浏览器旧版支持而存在?
这两种引用方法的主要区别是什么?
使用它们的好处有哪些?此外,它们分别最适合哪种使用情况?
var selection = document.querySelector('.selector') !== null;
var selection = document.querySelector('.selector');
前者是否仅为浏览器旧版支持而存在?
第一个示例先获取引用并检查元素是否存在,并将此状态保存为布尔值存储在变量中。如果元素存在,则变量包含true
,否则为false
。
如果您只想知道元素是否存在但不需要引用它,则可以使用第一个示例。
示例:
var selection = document.querySelector('.selector') !== null;
if (selection) {
alert('The element exists in the page.');
} else {
alert('The element does not exists in the page.');
}
第二个方法获取引用并将其存储在变量中,但是不会检查元素是否存在。如果元素存在,则变量包含对该元素的引用,否则变量包含null
。null
。var selection = document.querySelector('.selector');
if (selection !== null) {
alert('I have a reference to a ' + selection.tagName + ' element.');
} else {
alert('The element does not exists in the page.');
}
[].filter.call([document.querySelector('.single-selected-class')], item => item)
.forEach(item => item.blur());
document.querySelector('.selector')
是否为空。var selection = document.querySelector('.selector') !== null;
第二个语句包含了 document.querySelector('.selector');
的实际值。
var selection = document.querySelector('.selector');
var selection = document.querySelectorAll('.selector');
selection.forEach(function(item) {
alert(item);
});
注意! querySelectorAll()
的行为与大多数常见的 JavaScript DOM 库不同,这可能会导致意外的结果。
来源:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelectorAll
我曾为CMS EFFCORE开发了类似的解决方案,并得出了以下结论:
if (!Node.prototype.hasOwnProperty('querySelector__withHandler')) {
Object.defineProperty(Node.prototype, 'querySelector__withHandler', {
configurable: true,
enumerable : true,
writable : true,
value: function (query, handler) {
var result = this.querySelector(query);
if (result instanceof Node) {
handler(result);
}
}
});
}
document.querySelector__withHandler('a', function(link){
alert(link)
})
querySelector
是否在客户端浏览器中受支持。 - user5490177