2012-11-22 2 views
1

jQuery의 흥미로운 동작을 보았습니다. 그 이유는 무엇입니까? 나는 코드를 보면, 당신과 함께이를 공유 할 :다른 것들이 거짓으로 설정되기 전에 jQuery는 체크 된 입력을 얻지 못합니다.

  switch(id){ 
      case "1k": 
       check5k.attr('checked', false); 
       check10k.attr('checked', false); 
       check1k.attr('checked', true); 
       image1k.attr('class', 'radio-checked1k'); 
       image5k.attr('class', 'radio5k'); 
       image10k.attr('class', 'radio10k'); 
       break; 
      case "5k": 
       check1k.attr('checked', false); 
       check10k.attr('checked', false); 
       check5k.attr('checked', true); 
       image1k.attr('class', 'radio1k'); 
       image5k.attr('class', 'radio-checked5k'); 
       image10k.attr('class', 'radio10k'); 
       break; 
      case "10k": 
       check1k.attr('checked', false); 
       check5k.attr('checked', false); 
       check10k.attr('checked', true); 
       image1k.attr('class', 'radio1k'); 
       image5k.attr('class', 'radio5k'); 
       image10k.attr('class', 'radio-checked10k'); 
       break; 
     } 

그래서, 내가 alert($("input:checked").val())하려고 할 때 내가 같이한다면, 그것은 나에게 현재 선택한 라디오 값을 표시하지만, 작동 :

  switch(id){ 
      case "1k": 
       check1k.attr('checked', true); 
       check5k.attr('checked', false); 
       check10k.attr('checked', false); 
       image1k.attr('class', 'radio-checked1k'); 
       image5k.attr('class', 'radio5k'); 
       image10k.attr('class', 'radio10k'); 
       break; 
      case "5k": 
       check1k.attr('checked', false); 
       check5k.attr('checked', true); 
       check10k.attr('checked', false); 
       image1k.attr('class', 'radio1k'); 
       image5k.attr('class', 'radio-checked5k'); 
       image10k.attr('class', 'radio10k'); 
       break; 
      case "10k": 
       check1k.attr('checked', false); 
       check5k.attr('checked', false); 
       check10k.attr('checked', true); 
       image1k.attr('class', 'radio1k'); 
       image5k.attr('class', 'radio5k'); 
       image10k.attr('class', 'radio-checked10k'); 
       break; 
     } 

동일하게 만들려고 시도합니다. alert($("input:checked").val())은 (는) 10k ID와 다른 ID 만 표시합니다. 정의되지 않은 것으로 표시됩니다. 이 경우에 실제로 설정된 값이 마지막 값이기 때문에 값을 표시합니다.

왜 발생합니까?

답변

0

선택 속성을 잘못 설정했습니다. jQuery에서 설정하려면 .attr('checked', 'checked')을 설정하고 설정을 해제하려면 .removeAttr('checked') *

* jQuery 1.6 이전. 1.6 이후에는 prop을 사용합니다.

+0

jQuery의 버전에 따라 다릅니다. 그렇지만 1.6 이후 .attr()을 사용하면'checked'가되고 .prop()를 사용하면'true'가됩니다. – devnull69