我对javascript很新,并不确定我在做什么。现在我正在尝试将文本框数据以及一些字符串添加到cookie以显示在另一个页面上。文本框部分正在运行。
对于字符串,我正在使用单选按钮的值(用于多选测验验证),如果该值是该组的正确值,我想在cookie中添加一个字符串。我无法弄清楚这部分我做错了什么。
具体而言,不起作用的是gradeit()函数中的内容
JS档案
var total = 5;
var right = 0;
//cookies
function addToCookie(id, value)
{
document.cookie = id + escape(value);
}
var grade=new Array()
function gradeit(){
if(document.getElementById('correctOne').checked)
{
right++;
addToCookie("Q1 - Correct",right);
}
else {addToCOokie("Q1 - Incorrect", right);}
}
function checkCookie() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
addToCookie("First Name= ",firstName);
addToCookie("Last Name= ",lastName);
addToCookie("Email=",email);
}
window.onload = function () {
var elem = document.getElementById("submit");
elem.addEventListener('click', checkCookie);
}
// determine whether there is a cookie
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
var result = "";
// Now take key value pair out of this array
for (var i = 0; i < cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
result +=( name + " is : " + value)+"<br>";
}
document.writeln(result);
HTML PAge
<DOCTYPE HTML5>
<html>
<head>
<meta charset="utf-8">
<title>Quiz</title>
<script src="cookies.js" type="text/javascript"></script>
</head>
<body>
<h1><b>Multiple Choice Quiz</b></h1>
<form name="myquiz" action="answers.html" method="post">
<h2>Please Enter the Following:</h2>
First Name: <input type="text" id="fname"></input>
Last Name: <input type="text" id="lname"></input><br><br>
Student Email: <input type="email" id="email"></input>
<br>
<h3>#1. What is the capital of Iowa?</h3>
<input type="radio" name="question1" id="correctOne">Des Moines</input>
<input type="radio" name="question1" id="wrong">Los Angeles</input>
<input type="radio" name="question1" id="wrong">Paris</input>
<input type="radio" name="question1" id="wrong">Tokyo</input>
<br><br>
<input type="submit" id="submit" value="Submit Answers" onClick="gradeit()"></input>
</form>
</body>
</html>
答案 0 :(得分:0)
我只是通过这种方式修改我的gradeit()函数来实现它:
function gradeit(){
var ans = "";
if(document.getElementById('correctOne').checked)
{
//document.getElementById("output").innerHTML = "Q1 - Correct";
right++;
ans ="Right";
addToCookie("Q1 - ", ans);
}
else {
ans ="Wrong";
addToCookie("Q1 - ", ans);
}
}