gpt4 book ai didi

javascript - 询问用户名并发布到网站 "Hello XXX, welcome"

转载 作者:行者123 更新时间:2023-11-30 12:57:08 25 4
gpt4 key购买 nike

所以我从 W3Cschools 借用了代码(以防它看起来很熟悉),然后开始根据我的需要对其进行修改。基本上,我有一个默认的 H1 header “欢迎来到我的沙箱”。有一个将用户名保存到 cookie 的弹出窗口。如果它检测到名称/cookie/变量,则 H1 header 会更改为“欢迎(用户名)到我的沙箱”。我无法让(用户名)在第一页加载时显示,但它总是在第二页加载时有效。有什么想法吗?

代码如下:

            function getCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}
else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1){
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}

function setCookie(c_name,value,exdays){
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie(){
var username=getCookie("username");
if (username!=null && username!=""){
alert("Welcome again " + username);
document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
}
else{
username=prompt("Please enter your name:","");
if (username!=null && username!=""){
setCookie("username",username,365);
}
}
}

<body onload="checkCookie()" class="background_color">
<div class="wrap">
<h1 class="title" id="title_script">Welcome to my Sandbox</h1>

</div>

最佳答案

Your code is perfectly fine. You just missed a single line to use it again.

 document.getElementById("title_script").innerHTML = "Welcome " + username + "to my Sandboxx";

Use like this

 function checkCookie() {
var username = getCookie("username");
if (username != null && username != "") {
alert("Welcome again " + username);
document.getElementById("title_script").innerHTML = "Welcome " + username + " to my sandbox";
}
else {
username = prompt("Please enter your name:", "");
if (username != null && username != "") {
setCookie("username", username, 365);
document.getElementById("title_script").innerHTML = "Welcome " + username + "to my Sandboxx";
}
}
}

关于javascript - 询问用户名并发布到网站 "Hello XXX, welcome",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18650656/

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