我正在尝试使用 localstorage 为 ipad 应用程序创建测验。我已经成功创建了一个可以记住您单击的选项的测验,我可以检查答案是否正确。
但是,对于某些问题有多个答案,我希望能够将多个答案存储为该问题的数组。
我的测验当前将答案存储在由父 div 的类命名的键下。答案取决于您单击哪个 LI。请参阅下面的代码。
我想要能够为每个问题存储多个答案的选项,我将如何根据我拥有的代码执行此操作?我对javascript很陌生。
<!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>