私はこれを持っています: http://jsfiddle.net/ptWn/
<pre>
/*HTML*/
`<label class="for_radio"><input type="radio"><span>radio-button-1</span></label>`
`<label class="for_radio"><input type="radio"><span>radio-button-2</span></label>`
/*jQuery*/
$(document).ready(function(){
$('input[type="radio"]').click(function() {
if($('input[type="radio"]').is(':checked')) {
$(this).closest('label').addClass('active');}
else {
$(this).closest('label').removeClass('active');
}
});
});
/*CSS*/
.active {
background: #ffc;
}
</pre>
...ラジオボタンが選択されたときにラベルの背景色が変わるという意味で機能しますが、ラジオボタンの1つがチェックされていないときに背景色を変更する.activeクラスを削除する方法がわかりません。また、jsfiddle では、何らかの理由で、別のラジオ ボタンをクリックしても、別のラジオ ボタンが選択解除されません。
理由を理解するのに苦労している 2 番目のことは、if ステートメントの前に .click(function() が必要なように思われる理由です。
if($('input[type="radio"]').is(':checked')) {
$(this).closest('label').addClass('active');}
... JS スニペットとして単独では機能しません。なんで?
洞察をいただければ幸いです。ありがとう。