2014-02-23 123 views
0

這裏是我想要一個簡單的「addClass」的功能,但它不工作。應該是一個簡單的事情,坐在代碼中的某處)))。文本應該改變基於用戶在radioGroup1選擇的顏色在這裏http://jsfiddle.net/PatrickObrian/gdb5t/addClass不工作

HTML

<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} 

提前感謝!

回答

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

哦謝謝!!!!我必須包含jQuery的addClass功能嗎? – Alexander

+1

@Alexander'$'表示'jQuery'。如果你使用它,它必須包括在內。 –

+0

啊,我明白了,謝謝。剛開始使用Javascript。 – Alexander