JavaScript: querySelector Null vs querySelector

32

这两种引用方法的主要区别是什么?

使用它们的好处有哪些?此外,它们分别最适合哪种使用情况?

var selection = document.querySelector('.selector') !== null;

var selection = document.querySelector('.selector');

前者是否仅为浏览器旧版支持而存在?


2
第一个返回布尔值,第二个返回对象或null。这是你想知道的吗? - Artyom Neustroev
1
是的,也许需要更深入一些。什么是布尔值?它和对象有什么区别? - user3143218
布尔是“真/假”的另一个词。 - Álvaro González
请注意,您可以检查 querySelector 是否在客户端浏览器中受支持。 - user5490177
5个回答

80

第一个示例先获取引用并检查元素是否存在,并将此状态保存为布尔值存储在变量中。如果元素存在,则变量包含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.');
}

5
你也可以这样做:
[].filter.call([document.querySelector('.single-selected-class')], item => item)
    .forEach(item => item.blur());

3
第一条语句包含一个布尔值,取决于document.querySelector('.selector')是否为空。
var selection = document.querySelector('.selector') !== null;

第二个语句包含了 document.querySelector('.selector'); 的实际值。

var selection = document.querySelector('.selector');

2
你可以尝试使用以下方法避免条件语句:
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


0

我曾为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)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接