第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

元素已從 DOM 中消失,但是使用變量時條件語句仍然可以看到該元素

元素已從 DOM 中消失,但是使用變量時條件語句仍然可以看到該元素

幕布斯6054654 2023-06-29 21:19:23
為什么當使用完整的 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 語句在使用變量時不起作用?
查看完整描述

1 回答

?
阿晨1998

TA貢獻2037條經(jīng)驗 獲得超6個贊

發(fā)生這種情況是因為 document.querySelector 返回一個 HtmlElement 對象,該對象表示 dom 中的第一個匹配元素。該對象實際上并不是 dom 元素本身。


調(diào)用時,Element.remove()您從其所屬的樹中刪除節(jié)點,但元素本身仍保留在分配給變量的內(nèi)存中LoadMoreButton。如果您希望變量LoadMoreButton從 dom 中刪除后為 null,則可以為其賦值 null。


var LoadMoreButton = document.querySelector('.loadMore');


setInterval(function () {

  LoadMoreButton.remove();

  LoadMoreButton = null;

}, 10000);


var timer = null;


timer = window.setInterval(function () {

  if (LoadMoreButton !== null) {

    LoadMoreProducts();

  } else if (LoadMoreButton === null) {

    StopLoadingProducts();

  }

}, 1000);


function LoadMoreProducts() {}


function StopLoadingProducts() {

  clearInterval(timer);

}


查看完整回答
反對 回復(fù) 2023-06-29
  • 1 回答
  • 0 關(guān)注
  • 199 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號