为什么当使用完整的 JavaScript 选择器时,用于检查元素存在的间隔的“if 语句”工作正常,但当将其作为变量传递时,IF 语句认为该元素仍然存在,但事实并非如此?
两个例子来说明问题;首先,带有完整 JS 选择器的工作版本:
var LoadMoreButton = document.querySelector('.loadMore');
setInterval(function(){ LoadMoreButton.remove(); }, 10000);
var timer = null;
timer = window.setInterval(function(){
console.log(LoadMoreButton);
if (document.querySelector('.loadMore') !== null) {
console.log("Element still exists, load more...");
LoadMoreProducts();
} else if(document.querySelector('.loadMore') === null) {
console.log("Element does not exist.");
StopLoadingProducts();
}
}, 1000);
function LoadMoreProducts(){
console.log("LoadMoreProducts Function ran");
}
function StopLoadingProducts(){
console.log("No more products to load");
clearInterval(timer);
console.log("End.");
}
<button class="loadMore">Load More</button>
以及带有变量的无效版本。即使该元素早已消失,控制台也会输出该元素!
var LoadMoreButton = document.querySelector('.loadMore');
setInterval(function(){ LoadMoreButton.remove(); }, 10000);
var timer = null;
timer = window.setInterval(function(){
console.log(LoadMoreButton);
if (LoadMoreButton !== null) {
console.log("Element still exists, load more...");
LoadMoreProducts();
} else if(LoadMoreButton === null) {
console.log("Element does not exist.");
StopLoadingProducts();
}
}, 1000);
function LoadMoreProducts(){
console.log("LoadMoreProducts Function ran");
}
function StopLoadingProducts(){
console.log("No more products to load");
clearInterval(timer);
console.log("End.");
}
<button class="loadMore">Load More</button>
为什么我的 if 语句在使用变量时不起作用?
阿晨1998
相关分类