function sync_data() { localStorage.setItem("syncDataClicked", true); location.reload(); } window.onload = function () { if (localStorage.getItem("syncDataClicked") === "true") { localStorage.removeItem("syncDataClicked"); sync_data('show'); } };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <input type="submit" name="submit3" onclick="sync_data()" value="Sync data"> </body> </html>
Html: <input type="submit" name="submit3" onclick="sync_data()" value="Sync data"> JS: function sync_data() { window.onload = function () { setTimeout(function () { sync_data('show'); }, 5000); } }
這個js不工作。 onclick 和頁面重新載入後,我需要透過函數sync_data() 新增彈出視窗。有什麼辦法可以解決嗎。我已使用本地存儲進行更新,但它顯示彈出訊息
P粉5174756702023-09-10 00:59:58
您的window.onload函數已經在sync_data函數內。因此 window.onload 不會被觸發,因為點擊按鈕時頁面已經載入。所以你的window.onload函數應該在執行sync_data函數之前執行。所以在sync_data函數中你應該包含flag。根據該標誌,window.onload 函數將被觸發。您可以使用 localStorage 來儲存標誌。這是我的建議代碼。我不確定它是否有效。我將自訂彈出警報添加到代碼中。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sync Data</title> <script> function sync_data() { localStorage.setItem("syncDataClicked", true); location.reload(); } window.onload = function () { if (localStorage.getItem("syncDataClicked") === "true") { localStorage.removeItem("syncDataClicked"); showPopup(); } }; function showPopup() { alert('Data synced!'); } </script> </head> <body> <input type="submit" name="submit3" onclick="sync_data()" value="Sync data"> </body> </html>
P粉9905682832023-09-10 00:04:19
您可以使用以下程式碼:
function sync_data(string) { localStorage.setItem("syncDataClicked", string); location.reload(); } try{ if (localStorage.getItem("syncDataClicked")){ let popup = new Blob([localStorage.getItem("syncDataClicked")],{type: "text/html"}); let link = document.createElement("a"); let url = window.URL.createObjectURL(popup); link.href = url; link.target= "_blank"; link.click(); localStorage.removeItem("syncDataClicked"); } } catch (e) {console.log("It's the first time"); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> </head> <body> <input type="submit" name="submit3" onclick="sync_data('show')" value="Sync data"> </body> </html>