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>