これが解決策です。具体的には、HTML にいくつかの変更を加える必要があります。
- すべての回答に同じクラスを割り当てます ( true )
- 各回答に一意のクラスまたは 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