2013-06-26 8 views
4

기본적으로 확인란을 선택/선택 해제 할 때 이미지를 바꾸려고하는데 이미지를 두 번 클릭하면 "선택 취소"가 발생하지 않는 이유를 알 수 없습니다 (콘솔 "UNcheck it"이라고 인쇄하지 않음).이미지를 체크 박스 자리 표시 자로 사용

HTML :

<div id="inventory"> 
    <div class="nav"> 
     <div class="categories"> 
      <input type="checkbox" name="category" value="top"> 
      <input type="checkbox" name="category" value="bottom"> 
      <input type="checkbox" name="category" value="shoes"> 
      <input type="checkbox" name="category" value="accessories"> 
      <input type="checkbox" name="category" value="hairstyles"> 
      <input type="checkbox" name="category" value="eyes"> 
      <input type="checkbox" name="category" value="heads"> 
      <input type="checkbox" name="category" value="skins"> 
      <input type="checkbox" name="category" value="avatars"> 
      <a href="#" class="placeholder top"></a> 
      <a href="#" class="placeholder bottom"></a> 
      <a href="#" class="placeholder shoes"></a> 
      <a href="#" class="placeholder accessories"></a> 
      <a href="#" class="placeholder hairstyles"></a> 
      <a href="#" class="placeholder eyes"></a> 
      <a href="#" class="placeholder heads"></a> 
      <a href="#" class="placeholder skins"></a> 
      <a href="#" class="placeholder avatars"></a>     
     </div> 
    </div> 
</div> 


JS/jQuery를이 :

$('#inventory .nav .categories .placeholder').click(function(e){ 
    e.preventDefault(); 
    var category = $(this).attr('class').split(' ')[1]; //Grab second class of the clicked placeholder 
    var relatedCheckbox = $('#inventory .nav .categories input[value="' + category + '"]'); //find the actual related checkbox 
    if (relatedCheckbox.prop('checked', false)) { //if the related checkbox is unchecked... 
     console.log('check it!'); 
     relatedCheckbox.attr('checked', 'checked') //check it! 
    } else { //if it is already checked 
     console.log('UNcheck it!'); 
     relatedCheckbox.removeAttr('checked'); //uncheck it 
    } 
}) 

답변

3

그것은 당신의 prop() 방법입니다. 지금은 거짓 여부를 확인해야 할 때 checked 속성을 false로 지정합니다.

if (!relatedCheckbox.prop('checked')) { 
    relatedCheckbox.prop('checked',true) // <--use this to check it 
} else { 
    relatedCheckbox.prop('checked',false) // <-- use this to uncheck it 
} 

Example scenario

관련 문제