<分区>
我想简化这段代码并希望得到任何建议。
页面结构:
- 有 10 个不同的部分。
- 每个部分都有一个问题。
- 每个问题都有三个答案。
- 每个答案都有一个复选框。
- 当用户选中复选框时,会显示针对该特定答案的反馈。
- 当用户选中另一个复选框时,所有其他答案和复选框都会重置。
我已经在功能上创建了三个函数来完成这项工作。每个答案一个。为了使每个部分都能正常工作,我需要创建 30 个函数。我确信有更简单的方法,我只是不确定从哪里开始。
我的代码
// Action 1
$('.choice input.choice-a:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-1 .mod3-6-1_choice_A .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-1 .mod3-6-1_choice_A .mod3-6-1_feedback").focus();
});
$('.choice input.choice-b:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-1 .mod3-6-1_choice_B .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-1 .mod3-6-1_choice_B .mod3-6-1_feedback").focus();
});
$('.choice input.choice-c:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-1 .mod3-6-1_choice_C .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-1 .mod3-6-1_choice_C .mod3-6-1_feedback").focus();
});
// Action 2
$('.choice input.choice-a:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-2 .mod3-6-1_choice_A .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-2 .mod3-6-1_choice_A .mod3-6-1_feedback").focus();
});
$('.choice input.choice-b:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-2 .mod3-6-1_choice_B .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-2 .mod3-6-1_choice_B .mod3-6-1_feedback").focus();
});
$('.choice input.choice-c:checkbox').on('change', function(){
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);
hide_choices();
$("#action-2 .mod3-6-1_choice_C .mod3-6-1_feedback").removeClass("screen-reader");
$("#action-2 .mod3-6-1_choice_C .mod3-6-1_feedback").focus();
});
Action 1 和 Action 2 之间唯一不同的是向用户显示反馈的父 div。