【发布时间】:2012-10-12 18:59:41
【问题描述】:
我想简化这段代码,并希望得到任何建议。
页面结构:
- 有 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 向用户显示反馈。
【问题讨论】:
-
查看codereview.stackexchange.com。那会是一个更好的地方问这个问题。
-
发布与此相关的 HTML,或者更好地制作一个 jsFiddle。
标签: javascript jquery input checkbox