假设您的 HTML 具有逻辑结构,例如:
<form action="#" method="post">
<fieldset>
<legend>Question 1: gender</legend>
<label for="m">Male</label>
<input type="radio" name="gender" id="m" />
<label for="f">Female</label>
<input type="radio" name="gender" id="f" />
</fieldset>
<fieldset>
<legend>Question title</legend>
<!-- answer options -->
</fieldset>
<!-- other questions... -->
</form>
那么我能想到的最简单的选择如下:
$('form').on('click','input',
function(){
var fieldset = $(this).closest('fieldset');
fieldset.fadeOut(500,
function(){
fieldset.next('fieldset').fadeIn(500);
});
});
<a href="http://jsfiddle.net/davidThomas/sQW79/1/" rel="nofollow">JS Fiddle 演示。
为了允许重新审视以前的问题,我建议按照以下方式进行调整:
<form action="#" method="post">
<fieldset>
<legend>Question 1: gender</legend>
<label for="m">Male</label>
<input type="radio" name="gender" id="m" />
<label for="f">Female</label>
<input type="radio" name="gender" id="f" />
<div class="controls">
<a href="#" class="prev">Previous</a>
<a href="#" class="next">Next</a>
</div>
</fieldset>
<!-- other questions... -->
</form>
再加上jQuery:
$('fieldset').not($('fieldset:eq(0)')).hide();
$('.controls a.prev:first, .controls a.next:last').addClass('disabled');
$('form').on('click', 'input, a', function(e) {
var target = e.target,
targetType = target.tagName.toLowerCase(),
targetClass = target.className,
fieldset = $(this).closest('fieldset'),
prev = fieldset.prev().length,
next = fieldset.next().length;
if (targetType == 'input' && next > 0) {
fieldset.fadeOut(500, function() {
fieldset.next('fieldset').fadeIn(500);
});
}
else if (targetType == 'a') {
if (targetClass == 'prev' && prev > 0) {
fieldset.fadeOut(500, function() {
fieldset.prev('fieldset').fadeIn(500);
});
}
else if (targetClass == 'next' && next > 0) {
fieldset.fadeOut(500, function() {
fieldset.next('fieldset').fadeIn(500);
});
}
}
});
JS 小提琴演示。
参考:
jQuery的东西:
原生 JavaScript 的东西: