[英]Javascript prompt loads before page displays
I added a prompt on my page but it loads before the page has loaded.我在我的页面上添加了一个提示,但它在页面加载之前加载。 How do I only show the message once the whole page is visible?
一旦整个页面可见,我如何只显示消息?
Here is my prompt:这是我的提示:
if (name == null || name == "") {
txt == "No name provided";
} else {
txt = "Hello, " + name + "! How are you today?";
}
alert(txt);
If you wrap the code in an event-listener that listens for the DOMContentLoaded
event it'll run only once the document is ready:如果您将代码包装在侦听
DOMContentLoaded
事件的事件侦听器中,它将仅在文档准备好后运行:
window.addEventListener('DOMContentLoaded', (e)=>{
if (name == null || name == "") {
txt == "No name provided";
} else {
txt = "Hello, " + name + "! How are you today?";
}
alert(txt);
});
I have, however, adjusted your original code to:但是,我已将您的原始代码调整为:
window.addEventListener('DOMContentLoaded', (e) => { // assign the name via the prompt() interface, and // declare both variables (rather than accidentally // creating globals): let name = prompt("Hi, what's your name?"), txt; // name won't be null, but it may be falsey, so here // we check if the name is falsey: if (!name) { // if the user cancels the prompt, prompt() returns // false; if they provide an empty-string that // empty string is falsey: txt = "No name provided"; // if the name variable is truthy: } else { // we use a template literal String to interpolate // the variable 'name' into that string: txt = `Hello, ${name}! How are you today?`; } // I wouldn't recommend alert, but I left this unchanged: alert(txt); });
References:参考:
So to solve the problem of prompt loads before page displays:所以要解决页面显示前提示加载的问题:
script
tag just before the closing </body>
not in the <head>
tag.script
标签放在结束</body>
之前,而不是在<head>
标签中。DOMContentLoaded
& addEventListener
or simply with window.onload
. DOMContentLoaded
和addEventListener
或简单地使用window.onload
来收听DOM 。One of the simplest ways of doing this must be: window.onload = alert("text");
执行此操作的最简单方法之一必须是:
window.onload = alert("text");
. . Also, consider placing the code just before the closing
body
tag or using an event listener of some kind for further control over the message display.此外,请考虑将代码放在结束
body
标记之前或使用某种事件侦听器来进一步控制消息显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.