2016-11-17 167 views
1

https://jsfiddle.net/8g94ykta/jQuery的單選按鈕並不僅僅在第二/第三次點擊在第一次點擊觸發事件

單選框火災事件,只只顯示第一個結果。如何解決它?謝謝。

<input type="radio" name="group" checked="checked" value="first">A 
<input type="radio" name="group" value="second">B 
<input type="radio" name="group" value="third">C 
<p> 
<span id="result">-</span> 
</p> 



$('input[type="radio"][name=group]:checked').click(function(){ 
     if (this.value=='first') { 
      $("#result").text("first value");} 
     else if (this.value=='second') { 
       $("#result").text("second value");} 
     else if (this.value=='third') { 
       $("#result").text("third value");} 

    }); 

回答

0

請試試這個:$('input[type="radio"][name=group]'),而不是$('input[type="radio"][name=group]:checked')

您需要觸發click事件所有radio元素

$('input[type="radio"][name=group]').click(function(){ 
    if (this.value=='first') { 
     $("#result").text("first value");} 
    else if (this.value=='second') { 
     $("#result").text("second value");} 
    else if (this.value=='third') { 
     $("#result").text("third value");}     
}); 
0

你的選擇只是附加一個click處理程序當前選中的元素,所以它只會在你單獨點擊該元素時觸發。您需要將其附加到所有元素上:

$('input[type="radio"][name=group]').click(function() { 
相關問題