2015-09-05 133 views
0

的Javascript:錯誤答案單選按鈕

function radioResult(){ 
 
\t var r = document.getElementsByName('0'); 
 
\t for(var i = 0; i < r.length; i++){ 
 
\t \t if(r[i].checked){ 
 
\t \t \t rValue = r[i].value; 
 
\t \t \t if(rValue!='1') { 
 
\t \t \t \t r.style.backgroundColor='blue'; 
 
\t \t \t } else { 
 
\t \t \t \t alert('correct'); 
 
\t \t \t } 
 
\t \t } 
 
\t } 
 
\t qNo++; 
 
\t aCount2++; 
 
}
<input type='radio' name='0' value='1'>a<br> 
 
<input type='radio' name='0' value='2'>b<br> 
 
<input type='radio' name='0' value='3'>c<br> 
 
<input type='radio' name='0' value='4'>d<br> 
 
<hr> 
 
<button id="Mcqsbtn" onclick="radioResult()">Result</button>

的更改背景顏色我想radion按鈕改變爲藍色背景,如果答案是假的。怎麼做。 http://jsfiddle.net/mhabib555/k3h9c046/

更新

謝謝你們。我解決它通過你的幫助

+0

不能更改無線輸入元件,從而容易的CSS屬性。檢查這個:http://webdesign.tutsplus.com/articles/quick-tip-easy-css3-checkboxes-and-radio-buttons--webdesign-8953你將需要標籤,以及更多的東西。 – sinisake

回答

1

首先,你會想針對實際元素即..

r[i].style.backgroundColor='blue'; 

這將屬性應用到你的元素,但單選按鈕沒有被設計成具有背景色。我建議你用div填充每個按鈕,並改爲使用div。

function radioResult(){ 
 
\t var r = document.getElementsByName('0'); 
 
\t for(var i = 0; i < r.length; i++){ 
 
\t \t if(r[i].checked){ 
 
\t \t \t rValue = r[i].value; 
 
\t \t \t if(rValue!='1') { 
 
\t \t \t \t r[i].parentElement.style.backgroundColor='blue'; 
 
\t \t \t } else { 
 
\t \t \t \t alert('correct'); 
 
\t \t \t } 
 
\t \t } 
 
\t } 
 
\t //qNo++; 
 
\t //aCount2++; 
 
}
.wrap{ 
 
    padding:5px; 
 
    }
<div class="wrap"> 
 
<input type='radio' name='0' value='1'>a<br> 
 
</div> <div class="wrap"> 
 
<input type='radio' name='0' value='2'>b<br> 
 
    </div> <div class="wrap"> 
 
<input type='radio' name='0' value='3'>c<br> 
 
    </div> <div class="wrap"> 
 
<input type='radio' name='0' value='4'>d<br> 
 
</div> 
 
<hr> 
 
<button id="Mcqsbtn" onclick="radioResult()">Result</button>

+0

謝謝。它爲我工作 –

+0

沒問題。樂意效勞。 – kurt

1

你可以參考

的Html

<div><input type='radio' name='0' value='1'>a</div> 
<div><input type='radio' name='0' value='2'>b</div> 
<div><input type='radio' name='0' value='3'>c</div> 
<div><input type='radio' name='0' value='4'>d</div>  
<hr> 
<button id="Mcqsbtn" onclick="radioResult()">Result</button> 

的Javascript

function radioResult(){ 
    var r = document.getElementsByName('0'); 
    for(var i = 0; i < r.length; i++){   
     if(r[i].checked){ 
      rValue = r[i].value; 
      if(rValue!='1') { 
       r[i].parentNode.style.backgroundColor='blue'; 
      } else { 
       alert('correct'); 
      } 
     } 
    } 

} 

請參閱fiddle

Explainati on

您必須設置特定單選按鈕的background-color。因此,您應該使用r[i].style.backgroundColor='blue'而不是r.style.backgroundColor='blue'

0

目標作爲元素:

r[i].parentElement.style.backgroundColor='YourColor';