这两种参考方法的主要区别是什么?
使用一个或另一个的好处是什么?另外,他们每个人最适合的是哪种用法?
var selection = document.querySelector('.selector') !== null;
var selection = document.querySelector('.selector');前者是否仅用于浏览器遗留支持?
发布于 2014-04-10 11:49:39
第一个获取引用并检查元素是否存在,并将此状态保存为变量中的布尔值。如果元素存在,则变量包含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.');
}发布于 2017-03-01 12:49:01
你也可以:
[].filter.call([document.querySelector('.single-selected-class')], item => item)
.forEach(item => item.blur());发布于 2014-04-10 11:48:28
第一个语句包含依赖于document.querySelector('.selector')的bool值为空或不为空。
var selection = document.querySelector('.selector') !== null;第二个语句包含document.querySelector('.selector');的实际值。
var selection = document.querySelector('.selector');https://stackoverflow.com/questions/22987071
复制相似问题