我想简化这个代码,并喜欢任何建议。
页面的结构:
我在功能上创建了这个功能,使它能够在三个函数中工作。每个答案一个。为了使每个部分都能工作,我需要创建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。
发布于 2012-10-12 19:07:07
一个简单的改进是使用单选按钮而不是复选框,您可以删除这些行:
$('.choice input:checkbox').attr('checked', false);
$(this).attr('checked', true);编辑。这是我尝试的方法。输入元素需要数据-action=“1”和数据选择=“A”属性。
$('.choice input').on('change', function(){
var action = $(this).data('action');
var choice = $(this).data('choice');
$("#action-" + action).find(".mod3-6-1_choice_" + choice).find(".mod3-6-1_feedback").removeClass("screen-reader").focus();
});https://stackoverflow.com/questions/12865438
复制相似问题