我目前正在记录一个 li 的点击并用 localStorage 存储它的内容。
我有一个带有多项选择答案的测验问题,该问题当前存储他们选择的答案,但如果他们改变主意,则会用他们最后点击的任何答案覆盖它。
这对于单选题非常有效,但对于允许多个答案的问题,这将不起作用。
我需要做的是能够记录所有点击并将它们存储为数组。
这是我现有的代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style type="text/css">
body{
text-align: center;
}
#questions{
margin: 0 auto;
width: 802px;
height: 602px;
}
/*look for any class that has the word slide in it*/
[class*="slide"]{
padding: 20px;
background: #666;
width: 760px;
height: 560px;
border: 1px dashed #333;
}
[class*="slide"]:nth-child(odd){
background: #999;
}
b{
position: absolute;
top: 10px;
}
</style>
</head>
<body>
<div id="questions">
<div class="slide1">
<h1>What is h2o?</h1>
<ul>
<li>A Pencil</li>
<li>Liquid water</li>
<li>A mobile phone network</li>
<li>Paper</li>
</ul>
<p>check</p>
</div>
<div class="slide2">
<h1>What is 2 + 2?</h1>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<p>check</p>
</div>
<div class="slide3">
<h1>What is a whale?</h1>
<ul>
<li>A mammal</li>
<li>A fish</li>
<li>A bird</li>
<li>A country</li>
</ul>
</div>
<div class="slide4">
<h1>What phone do you prefer?</h1>
<ul>
<li>iPhone 4s</li>
<li>iPhone 5</li>
</ul>
</div>
<div class="slide5">
<h1>What is 5 + 5?</h1>
<ul>
<li>10</li>
<li>7</li>
</ul>
</div>
<div class="slide6">
<h1>What is the capital city of England?</h1>
<ul>
<li>London</li>
<li>Staines</li>
<li>Bognor Regis</li>
<li>Luton</li>
</ul>
</div>
<div class="slide7">
<h1>What colour is a red phone box?</h1>
<ul>
<li>Blue</li>
<li>Red</li>
<li>Pink</li>
<li>Mauve</li>
</ul>
</div>
</div>
<b></b>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/*
//
// quiz storer and answer checker
// Author: Tjobbe Andrews
// v1.0, 13/02/2013
// - keeps a record in localStorage of the answers you chose, then checks them on an ad hoc basis
//
*/
//on clicking the answers in the li's..
$("li").click(function(){
//..create a variable called answer based on the content of that li..
var answer = $(this).html();
//..and create a variable called question based on the class of the parent div
var question = $(this).parent().parent().attr("class");
//then store the key value pair of question and answer
localStorage.setItem(question, answer);
//just makes sure that it's writing to the LS db
$("b").html(localStorage.getItem(question));
});
//click the p tag to check what we've got stored for this div - ad hoc
$('p').click(function(){
var slideNumber = $(this).closest('div').attr('class');
var answer = localStorage.getItem(slideNumber);
if(answer !== "Liquid water"){
alert('wrong');
}
else if(answer == "Liquid water"){
alert("right");
}
});
});
</script>
</body>
</html>