问题
i'm trying to make a simple quiz using jquery hide & show functions , first i created some divs elements wich will be the questions + the last elements will contain a text & a button to watch result (there will be no result) ; i'm using two buttons : next & prev .
So the things i can't do on my own are :
1- hide the two buttons when they show the last div (Of the result !) ;
2-make the prev buttons stop on the first question .
3- how i can implement bootstrap radio options with Jquery to store answers & show them at the last on the click of button.
$(document).ready(function(){
$(".divs div").each(function(e) {
if (e != 0)
$(this).hide();
});
$("#next").click(function(){
if ($(".divs div:visible").next().length != 0)
$(".divs div:visible").next().show().prev().hide();
else {
$(".divs div:visible").hide();
$(".divs div:first").show();
}
return false;
});
$("#prev").click(function(){
if ($(".divs div:visible").prev().length != 0)
$(".divs div:visible").prev().show().next().hide();
else {
$(".divs div:visible").hide();
$(".divs div:last").show();
}
return false;
});
});
<div class="divs">
<div class="cls1">1</div>
<div class="cls2">2</div>
<div class="cls3">3</div>
<div class="cls4">4</div>
<div class="cls5">5</div>
<div class="cls6">6</div>
<div class="cls7">7</div>
</div>
<a id="next">next</a>
<a id="prev">prev</a>
Thanks in advance guys !
回答1:
JSFiddle
HTML:
<div class="divs">
<div class="cls1">
Gender<br/>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</div>
<div class="cls2">
Language<br/>
<input type="radio" name="language" value="java">Java<br>
<input type="radio" name="language" value="python">Python
</div>
<div class="cls3">
Preference<br/>
<input type="radio" name="preference" value="morning">Morning<br>
<input type="radio" name="preference" value="night">Night
</div>
<div class="cls4">4</div>
<div class="cls5">5</div>
<div class="cls6">6</div>
<div class="cls7">7</div>
<div class="your-quiz-result"></div>
</div>
<a id="next">next</a>
<a id="prev">prev</a>
JavaScript:
$(document).ready(function(){
$(".divs > div").each(function(e) {
if (e != 0)
$(this).hide();
});
$("#next").click(function(){
if ($(".divs div:visible").next().length != 0){
$(".divs div:visible").next().show().prev().hide();
if($(".divs div:visible").next().length == 0){
//1. Hide the two buttons
$("#next, #prev").hide();
//3. Show the results
var divs = $(".divs div:visible").prevAll().clone();
divs.show();
//Reverse the order
var divs = jQuery.makeArray(divs);
divs.reverse();
$(".your-quiz-result")
.empty()
.append(divs);
}
}
return false;
});
$("#prev").click(function(){
if ($(".divs div:visible").prev().length != 0){
console.log("There are still elements");
$(".divs div:visible")
.prev()
.show()
.next()
.hide();
}
else {
//2. Can't go previous first div
console.log("Can't go previous first div");
}
return false;
});
});
来源:https://stackoverflow.com/questions/33057285/jquery-hide-show-to-build-quiz