簡體   English   中英

Run JavaScript function after the first function completes applying CSS styles to an element - callback not working

[英]Run JavaScript function after the first function completes applying CSS styles to an element - callback not working

如片段所示,我有兩個按鈕。 單擊任一按鈕時,應按此順序發生以下情況:(1) 顏色變為紅色,(2) 按鈕被隱藏 (3) 顯示帶有按鈕 ID 的警報框。

我嘗試將 function2 作為回調參數傳遞給 function1,但實際發生的是警報框首先顯示,然后按鈕消失而沒有顏色變化。

我不明白為什么會這樣。 任何幫助/提示將不勝感激!

 var items = document.getElementsByClassName("buttons"); for (var i = 0; i < items.length; i++) { items[i].addEventListener("click", function() { function1(this.id, function2); }); } function function1 (uid, callback) { document.getElementById(uid).style.backgroundColor = "red"; document.getElementById(uid).style.display = "none"; callback(uid); } function function2 (clicked_id) { alert(clicked_id); }
 <p>Clicking on a button should change its color to red, hide it and then display an alert box with the button's ID:</p> <div class="main"> <button id="btn1" class="buttons">Button 1</button> <button id="btn2" class="buttons">Button 2</button> </div>

在使用alert停止世界之前,您需要給瀏覽器的 UI 線程(這是您的 JavaScript 代碼運行的線程)時間來重新繪制頁面。 或者更好的是,根本不要使用alert

通常可以通過一個事件循環周期延遲它

setTimeout(callback, 0, uid);

...但不總是。 迄今為止我發現的最有效的方法(但我不必經常這樣做,因為我不經常使用 stop-the-world 函數alertconfirmprompt )是在 a 中使用setTimeout requestAnimationFrame調用:

requestAnimationFrame(() => {
    setTimeout(callback, 0, uid);
});

在應用您的更改后,在瀏覽器准備好重新繪制之前調用外部回調,因此我們在此之后安排調用。

更新片段:

 var items = document.getElementsByClassName("buttons"); for (var i = 0; i < items.length; i++) { items[i].addEventListener("click", function() { function1(this.id, function2); }); } function function1 (uid, callback) { document.getElementById(uid).style.backgroundColor = "red"; document.getElementById(uid).style.display = "none"; requestAnimationFrame(() => { setTimeout(callback, 0, uid); }); } function function2 (clicked_id) { alert(clicked_id); }
 <p>Clicking on a button should change its color to red, hide it and then display an alert box with the button's ID:</p> <div class="main"> <button id="btn1" class="buttons">Button 1</button> <button id="btn2" class="buttons">Button 2</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM