JavaScript:querySelector为空vs querySelector [英] JavaScript: querySelector Null vs querySelector
问题描述
这两种引用方法之间的主要区别是什么?
What is the main difference between these two methods of referencing?
使用一种或另一种有什么好处?另外,它们各自最适合哪种使用情况?
What are the benefits of using one or the other? Also what kind of usage-case would they each be best suited to?
var selection = document.querySelector('.selector') !== null;
var selection = document.querySelector('.selector');
前者是仅用于浏览器旧版支持吗?
Is the former solely for browser legacy support?
推荐答案
第一个获取引用并检查该元素是否存在,并将此状态另存为布尔值.如果该元素存在,则变量包含 true
,否则包含 false
.
The first one gets the reference and checks if the element exists, and saves this status as a boolean value in the variable. If the element exists, the variable contains true
otherwise false
.
如果只想知道元素是否存在,而又不需要引用它,则可以使用第一个.
You would use the first one if you only want to know if the element exists, but don't need the reference to it.
示例:
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
.
The second one gets the reference and stores in the variable, but doesn't check if the element exists. If the element exists, the variable contains the reference to the element, otherwise the variable contains null
.
如果需要引用该元素,则可以使用第二个.如果页面中可能不存在该元素,则应在尝试使用引用之前先检查该变量是否包含 null
.
You would use the second one if you need the reference to the element. If it's possible that the element doesn't exist in the page, you should check if the variable contains null
before you try to do something with the reference.
示例:
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.');
}
这篇关于JavaScript:querySelector为空vs querySelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!