2011-01-31 4 views
1

일부 jQuery 체크 박스 버튼이 있는데 제대로 작동합니다. 그러나 클릭 한 번으로 텍스트를 변경하고 싶습니다. 예 : 버튼의 텍스트는 "click me"입니다. 사용자가 그것을 클릭하면, 예를 들어, "클릭에 대한 감사"로 변경해야합니다.클릭하면 jQuery 변경 체크 박스 버튼 텍스트

<script> 
    $(function() { 
     $("#button").button(); 
     $("#button").click(function(){ 
      if($("#label").is(':checked')) { 
       $("#label span").text("Hide"); 
      } 
      else { 
       $("#label span").text("Show"); 
      } 
     }); 
    }); 
</script> 
<input id='button' type='checkbox' /> 
<label id='label' for="button">Show/Hide</label> 

답변

4

이 첫 번째 문제 :

 if($("#label").is(':checked')) { 

<label> 요소는하지 않는다 "확인"에만 체크 박스가 할

이것은 내가 사용하려하는 것이다. 로 변경 : 위의 코드에서

if (this.checked) { 

, this가 클릭 된 체크 박스 요소를 참조, 우리는 checked 속성 값 true이 포함되어 있는지 찾고 있습니다. .is(':checked')보다 훨씬 효율적입니다.

또한, <label> 요소가 더 <span> 아이가없는, 그냥 그렇게

  $("#label span").text("Hide"); 

  $("#label").text("Hide"); 

해야, 텍스트가하지만 당신은 conditional operator 삼항 사용하여 모든 일을 단축 할 수있다 :

$("#button").click(function(){ 
     $("#label").text(this.checked ? "Hide" : "Show"); 
    } 

워킹 데모 : 여기 http://jsfiddle.net/AndyE/qnrVp/

1
$("#button").click(function() { 
    if($(this).is(':checked')) { 
     $("#label").text("Hide"); 
    } else { 
     $("#label").text("Show"); 
    } 
}); 

그리고는 live demo입니다.

0

이 시도 :

$("#button").click(function(){ 
    var th = $(this); 
    if(th.is(':checked')) { 
      $("label[for=" + th.attr('id') + "]").text("Hide"); 
    } else { 
      $("label[for=" + th.attr('id') + "]").text("Show"); 
    } 
});