我想簡化這段代碼,並且會喜歡任何建議。頁面簡化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