2015-11-05 183 views
0

我有多個單選按鈕。在我有的代碼中,它們是與不同功能對應的不同圖片。單擊標籤的單選按鈕

用戶必須知道哪個單選按鈕被點擊。因此,我試圖找到一種方法來改變單擊按鈕後單選按鈕的背景。 爲了使代碼正常工作,<label>必須圍繞<input>標籤。

<div class="radio-toolbar"> 

     <label class="BottomLeft"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="BottomLeft" /> 
     </label> 

     <label class="BottomRight"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="BottomRight" /> 
     </label> 

     <label class="Dual"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="Dual" /> 
     </label> 

     <label class="DualRight"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="DualRight" /> 
     </label> 

     <label class="Duplex"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="Duplex" /> 
     </label> 

     <label class="Custom"> 
      <input id="tech" type="radio" ng-model="SelectedLayout" value="Custom" /> 
     </label> 
    </div> 

這裏的JSfiddle

+2

? 「id」的重點在於它允許你通過它的'id'來查找元素。但是,只有當你的'id's是唯一的。 –

+1

ID應該始終是唯一的 – guradio

+0

我有一段代碼,我通過ID獲取元素。由於他們都必須相互對應,所以我使用了相同的ID。這不是完美的方式,但我使用必要的代碼'initDropDown(document.getElementById('tech'));' – MarLen

回答

1

你可以試試這個:

$('input[type=radio]') 
    .on('click', function() { 
     var $label = $(this).closest('label'); 
     $('label').not($label).css('background-color', 'green'); 
     $label.css('background-color', '#2C8BDE'); 
}); 

這裏是FIDDLE

另外,您必須在html中有唯一的ID's。

+0

謝謝!感謝您的建議。我會改變ID的。 – MarLen

0

要使用您的標籤,您的代碼應該看起來像這樣。問題是,您無法爲所有元素使用相同的ID。 ID是唯一的,如果要使用標籤,則必須將for="#"屬性放入您的<label></label>元素中。因此,請記住<label></label>for=""屬性一起使用,並且for=""屬性與<input />標記中的id一起使用。並且我製作了您的單選按鈕不是多個,因此請刪除name=""屬性以使其成爲多個。

<div class="radio-toolbar"> 

      <label for="first"> 
       Tech<input id="first" type="radio" ng-model="SelectedLayout" name="radioButton" value="BottomLeft" /> 
      </label> 

      <label for="second"> 
       AnotherOne<input id="second" type="radio" ng-model="SelectedLayout" name="radioButton" value="BottomRight" /> 
      </label> 

      <label for="third"> 
       Third<input id="third" type="radio" ng-model="SelectedLayout" name="radioButton" value="Dual" /> 
      </label> 

      <label for="fourth"> 
       Fourth<input id="fourth" type="radio" ng-model="SelectedLayout" name="radioButton" value="DualRight" /> 
      </label> 

      <label for="fifth"> 
       Fifth<input id="fifth" type="radio" ng-model="SelectedLayout" name="radioButton" value="Duplex" /> 
      </label> 

      <label for="sixth"> 
       Sixth<input id="sixth" type="radio" ng-model="SelectedLayout" name="radioButton" value="Custom" /> 
      </label> 
     </div> 
0

儘量this。我已經改變backgorund爲什麼您使用的是相同的`id`您所有的輸入顏色檢查單選按鈕,橙色與jquery

$('input[type=radio]') 
    .on('click', function() { 
     var $label = $(this).closest('label'); 
     $('label').not($label).css('background-color', 'green'); 
     $label.css('background-color', '#2C8BDE'); 
});