大家好,我已经创建了我的代码,一旦用户填写表单并按下提交,它就会使用 cookie 记住该表单的偏好。
我的第一个问题是我不知道如何使用“init()”方法向用户打印消息。
我的第二个问题是,当用户返回同一页面时,我不知道如何根据用户填写的表单显示页面。(如果有人在返回页面后点击蓝色作为背景仍显示为蓝色)。我已经尝试通过记住名字并根据他们的选择更改颜色来做到这一点。
!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript">
function changeColour(buttonColour){
if (buttonColour =="red"){
document.body.style.backgroundColor = "#FF0000";
document.body.style.color = "#CCFFFF";
}else if(buttonColour == "blue"){
document.body.style.backgroundColor = "#0000FF";
document.body.style.color = "#CCFFFF";
}else if(buttonColour == "green"){
document.body.style.backgroundColor = "#009933";
document.body.style.color = "#CCFFFF";
}
}
expirydate.setDate(exdate.getDate()+numdays);
expirydate.toUTCString();
function setCookie(firstname){
var expirydate = new Date();
document.cookie = "firstname =" + encodeURIComponent(firstname);
expirydate.setDate(expirydate.getDate()+ 7*24*60*60*1000);
expirydate.toUTCString();
var checkedbox;
elementArray = document.getElementsByTagName("input");
console.log(elementArray);
for (var i =0; i<elementArray.length; i++){
if(elementArray[i].type="radio" && elementArray[i].checked){
checkedbox = elementArray[i].value;
alert(checkedbox);
document.cookie = "buttonColour" + "=" + encodeURIComponent(checkedbox);
}
}
}
function readCookie(firstname){
var namevalueArray = document.cookie.split(";");
for(var i =0; i< namevalueArray.length; i++){
var smallvalueArray = namevalueArray[i].trim().split("=");
if(smallvalueArray[0]== firstname){
document.cookie = "firstname" + decodeURIComponent(firstname);
return smallvalueArray[1];
}else{
return null;
}
}
function init(){
print("welcome =", firstname)
}
}
</script>
<script type="text/css">
#formsa{
width:300px;
height:400px;
position: absolute;
font-weight: bolder;
left:200px;
top:70px;
}
</script>
</head>
<body onload=init()>
<div id="formsa">
<form name="test" method="get" id="forms">
First name: <input type="text" name="firstname"><br>
Red colour: <input type="radio" name="buttonColour" value="red" onchange=
"changeColour('red');"><br>
Green colour: <input type="radio" name="buttonColour" value="green" onchange=
"changeColour('green');"><br>
Blue colour: <input type="radio" name="buttonColour" value="blue" onchange=
"changeColour('blue');"><br>
<button type="button" value="Save" id="saveButton" onclick=`enter code here`
"setCookie(firstname.value);">Save</button>
</div>
</form>
</body>
</html>
最佳答案
我不太确定我是否真的理解你正在尝试做的事情,但我会尝试给你一些指示...
- 当页面加载时,您可以像现在一样使用
init
函数 在
init
函数中,如果您想在用户脸上“打印”一条消息,那么您有两个选择...一个。通过设置 html 元素(例如标题)的
innerHTML
属性在页面上呈现“欢迎”消息...h1
、h2
、h3
等 b.通过“提醒”消息,我个人不喜欢这种方法,但它是使用alert
函数而不是使用print
做的任何事情的另一种选择,因为print
似乎没有在你的代码中定义,除非你试图打印到打印机......我怀疑,无论哪种方式,这都不是启动浏览器打印对话的正确方法在
init
函数中,您应该尝试以安全的方式检索 cookie- 如果 cookie 存在,检索它的值并相应地设置 html 元素
- 如果不存在,则按正常方式呈现页面
您已经编写了大部分用于读/写 cookie 和读/写 html 元素的逻辑。这只是在您的 init
函数中实现它们的问题
关于javascript - 使用 cookie 记住背景颜色并在从表单访问时显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23668390/