gpt4 book ai didi

在页面显示之前加载 Javascript 提示

转载 作者:行者123 更新时间:2023-12-02 15:49:43 27 4
gpt4 key购买 nike

我在我的页面上添加了一个提示,但它在页面加载之前加载了。如何仅在整个页面可见时才显示消息?

这是我的提示:

if (name == null || name == "") {
txt == "No name provided";
} else {
txt = "Hello, " + name + "! How are you today?";
}
alert(txt);



最佳答案

如果将代码包装在监听 DOMContentLoaded 事件的事件监听器中,它只会在文档准备好后运行:

window.addEventListener('DOMContentLoaded', (e)=>{
if (name == null || name == "") {
txt == "No name provided";
} else {
txt = "Hello, " + name + "! How are you today?";
}
alert(txt);
});

但是,我已经将您的原始代码调整为:

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);
});

JS Fiddle demo .

引用资料:

关于在页面显示之前加载 Javascript 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72937833/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com