2012-06-14 2 views
0

내가하려는 것은 사용자가 해당 테이블 내부의 라디오 버튼을 선택한 테이블을 클릭 한 다음 선택한 테이블에 클래스를 추가하게하는 것입니다. 그런 다음 라디오가 선택되었을 때 사용자가 다른 테이블을 선택하면 클래스가 추가되지만 이전에 선택한 테이블/라디오의 클래스도 제거해야합니다.이전에 선택한 라디오 버튼에서 클래스를 제거 할 수 없습니다.

지금 바로 그 대부분이 작동합니다. 다른 라디오를 선택하면 이전 수업이 삭제되지 않습니다. 라디오를 토글 한 경우에만 제거됩니다.

Here's a link to a demo on jsfidd 여기서 모든 HTML 및 기타 JS를 볼 수 있습니다.

$(function() { 

    $('table').click(function(event) { 

     if (event.target.type != "radio") { 

      var that = $(this).find('input:radio'); 

      that.attr('checked', !that.is(':checked')); 

      if (that.is(':checked')) { 
      that.closest('table').addClass('selected'); 
      } 
      else { 
       that.closest('table').removeClass('selected'); 
      } 
     } 

    }); 
}); 

내가 수정하기 전에 다른 버전을 사용하고 있다는 사실을 잊어 버렸습니다. 이 경우 실제로 라디오 버튼을 클릭하면 스타일이 올바르게 추가되거나 제거되지만 테이블을 클릭 할 때는 그렇지 않습니다. 나는이 두 가지를 결합하려고 시도했다. 내가 위에 게시 한 기능을 어떻게 얻었 는가.

그리고 여기 jquery도 사용했다.

// jQuery to select radio button within clicked table 
$(function() { 

$('table').click(function(event) { 

    if(event.target.type != "radio") { 

     var that = $(this).find('input:radio'); 
     that.attr('checked', !that.is(':checked')); 

    } 
}); 
}); 

// jQuery to change the style of the table containing the selected radio button 
$(function() { 
$('input[type="radio"]').change(function() { 
    // grab all the radio buttons with the same name as the one just changed 
    var this_radio_set = $('input[name="'+$(this).attr("name")+'"]'); 

    for (var i=0; i < this_radio_set.length;i++) { 
    if ($(this_radio_set[i]).is(':checked'))   
     $(this_radio_set[i]).closest('table').addClass('selected'); 
     else 
     $(this_radio_set[i]).closest('table').removeClass('selected'); 
} 
}); 
}); 

답변

0

이 같은 것을 수행해야합니다 :

$(this).closest('.container').addClass('selected').parent().siblings().each(function() { 
    $(this).find('.container').removeClass('selected'); 
}); 

그리고 데모 :

+0

http://jsfiddle.net/cGTYm/22/는 빠른 응답 주셔서 감사합니다. 내 if (if.is (': checked')) 내에서 그렇게하겠습니까? 나는 꽤 이해하지 못한다. – xxstevenxo

+0

데모 링크의 코드 위치를 확인하십시오. – Blender

+0

대단히 감사합니다! 그것은 완벽하게 작동했습니다! : DD – xxstevenxo

0
$(function() { 
    $('table').click(function(event) { 
     if (event.target.type != "radio") { 
      var that = $(this).find('input:radio'); 
      that.attr('checked', !that.is(':checked')); 

      $('table.selected').removeClass('selected'); 
      that.closest('table').addClass('selected'); 

     } 
    }); 
}); 
관련 문제