我想简化这段代码,并且会喜欢任何建议。页面简化JavaScript代码
结构:
- 有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();
});
动作1和动作2之间唯一不同的是显示反馈给用户的父DIV。
查看http://codereview.stackexchange.com/。这将是一个更好的地方来问这个问题。 – Travesty3
发布符合这个或更好的,但做一个jsFiddle的HTML。 – j08691