这是一个解决方案。它需要对您的 HTML 进行一些更改,特别是:
- 将所有答案分配到同一类(真)
- 为每个答案分配一个唯一的类或 ID:(tr1、tr2 等)
- 为每个问题分配相同的课程(你可以)
- 为每个问题分配一个唯一的类或 ID:(yc1、yc2 等)
- 将所有 div 变成兄弟姐妹,而不是孩子
工作 jsFiddle 示例
HTML:
<div id="result">
<div class="truth tr0"><h2>---</h2></div>
<div class="truth tr1"><h2>answer to one</h2></div>
<div class="truth tr2"><h2>answer to two</h2></div>
<div class="truth tr3"><h2>answer to three</h2></div>
<div class="truth tr4"><h2>answer to four</h2></div>
<div class="truth tr5"><h2>answer to five</h2></div>
<div class="truth tr6"><h2>answer to six</h2></div>
</div>
<div id="replaceLink">
<div class="youcould yc1">
<a href="#2"><h2>QUESTION ONE</h2></a>
</div>
<div class="youcould yc2">
<a href="#3"><h2>QUESTION TWO</h2></a>
</div>
<div class="youcould yc3">
<a href="#4"><h2>QUESTION THREE</h2></a>
</div>
<div class="youcould yc4">
<a href="#5"><h2>QUESTION FOUR</h2></a>
</div>
<div class="youcould yc5">
<a href="#5"><h2>QUESTION FIVE</h2></a>
</div>
<div class="youcould yc6">
<a href="#5"><h2>QUESTION SIX</h2></a>
</div>
<div class="youcould yc7">
<a href="#6"><h2>THANK YOU</h2></a>
</div>
</div>
<div id="response"></div>
<input type="button" id="mybutt" value="Start Test" />
Javascript/jQuery:
arrDone = [];
$(document).ready(function () {
//http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function nextQues() {
//If all six questions asked, quit
if (arrDone.length == 6) return 7;
success = 0;
while (success == 0) {
nn = getRandomInt(1, 6);
if (arrDone.indexOf(nn) == -1) {
success++;
arrDone.push(nn);
}
}
return nn;
}
$('.youcould, .truth').hide();
$('.tr0').show();
$('.youcould').click(function() {
$(this).hide();
//Get last-entered element from array
thisA = arrDone[arrDone.length -1];
$('.tr'+thisA).show();
});
$('.truth').click(function() {
$(this).hide();
if (arrDone.length == 6){
$(this).removeClass('truth');
$('#replaceLink').html('<div><h1>Test is Over.</h1><div>');
}else{
nextQ = nextQues();
$('.yc'+nextQ).show();
}
});
$('#mybutt').click(function () {
$(this).hide();
$('.tr0').hide();
nextQ = nextQues();
$('.yc'+nextQ).show();
});
}); //END document.ready