0
我有一個返回true或false的函數。現在我想在函數返回「true」時執行一些代碼。
該功能確定一個元素是否在屏幕上可見。我從here。
該元素在頁面加載後1-2秒後顯示。但是,因爲這也與用戶的互聯網連接有關,所以我不想使用setTimout函數。 我嘗試了幾件事,發現它在if/else語句中工作,但不在when/then中。任何想法,這裏出了什麼問題?
我測試了幾件事情,看到代碼
//below if else statement works fine and logs the correct result
if($(".myClass").isOnScreen()==true){
console.log("true");
}
else{console.log("false");}
//however i would like to use this one and it doesn't seem to work
$.when($(".myClass").isOnScreen()==true).then(function(){
console.log($(".myClass").isOnScreen());
setTimeout(function(){
console.log($(".myClass").isOnScreen());
},1000);
});
下面什麼時候/ then語句實際上做: 它儘快功能isOnScreen運行運行,但不會等到回反應是真實的。因此,控制檯日誌始終爲false。 然後我實現了一個timeOut(僅用於測試目的)。 timeOut運行完成後,控制檯日誌始終爲false。
它應該做什麼: 當結果變爲true時,應該運行when /語句。
'isOnScreen'看起來像一個**'sync' **操作,如果在承諾/超時把它包,您將以不一致的行爲結束...... – Hitmands
您鏈接的邏輯被設計爲在「scroll」事件處理程序中使用。它不會返回承諾,也不應該與其中一個使用 –