2014-02-23 2 views
0

여기에 간단한 "addClass"기능이 있지만 작동하지 않습니다. 코드 어딘가에 앉아있는 간단한 일))). 텍스트는 사전에addClass가 작동하지 않습니다.

<div class="test">Information that I want to be coloured</div> 
<div> 
    <label><input type="radio" id="A" name="RadioGroup1" value="Y">Yes</label> 
    <br> 
    <label><input type="radio" id="B" name="RadioGroup1" value="N">No</label> 
</div> 

JS

<script> 
$('input[type=radio][name=RadioGroup1]').change(function(){ 
if (this.value == 'Y') { 
     $('.test').addClass("classGreen"); 
} 
else if (this.value == 'N') { 
     $('.test').addClass("classRed"); 
} 
    } 


</script> 

CSS

.classGreen {color: green} 
.test {font-size:24px} 
.classRed {color: red} 

감사 HTML http://jsfiddle.net/PatrickObrian/gdb5t/

여기에 radioGroup1에서 사용자의 선택에 따라 색상을 변경해야합니다!

답변

1

당신은 수표 또한 클릭 이벤트 다른 색상 클래스 이름을 제거해야합니다

$('input[type=radio][name=RadioGroup1]').click(function(){ 
    if (this.value == 'Y') { 
     $('.test').removeClass("classRed").addClass("classGreen"); 
    } 
    else if (this.value == 'N') { 
     $('.test').removeClass("classGreen").addClass("classRed"); 
    } 
}); 

그리고 나도 몰라요. 그러나 이것은 CSS에서 작동했습니다 :

<style type="text/css"> 
.test { font-size:24px } 
.classRed { color: red } 
.classGreen { color: green } 
</style> 

:

5

이전에 연결된 클래스를 제거한 다음 새 클래스를 추가해야합니다.

jQuery(function() { 
    $('input[type=radio][name=RadioGroup1]').change(function() { 
     if (this.value == 'Y') { 
      $('.test').removeClass('classRed').addClass("classGreen"); 
     } else if (this.value == 'N') { 
      $('.test').removeClass('classGreen').addClass("classRed"); 
     } 
    }) 
}) 

데모 : Fiddle

또한 바이올린에

  • jQuery를이
  • 포함되지 않은 다른 많은 문제가 스타일 부분은 적절하지이었다 있었다
  • 구문 오류가 있었다

더 짧은 방법은 toggleClass()를 사용하는 것입니다

jQuery(function() { 
    $('input[type=radio][name=RadioGroup1]').change(function() { 
     $('.test').toggleClass("classGreen", this.value == 'Y'); 
     $('.test').toggleClass("classRed", this.value != 'Y'); 
    }) 
}) 

데모 : Fiddle

+0

오 감사합니다! addClass 기능을 위해 jQuery를 포함해야합니까? – Alexander

+1

@Alexander'$'는'jQuery'를 의미합니다. 그것을 사용한다면 반드시 포함시켜야합니다. –

+0

아, 고맙습니다. Javascript를 시작했습니다. – Alexander