2013-07-18 40 views
0

只有單選按鈕具有屬性data-price時,我需要執行一些計算。目前,所有單選按鈕始終執行計算。僅當元素具有特定屬性時才執行更改事件

我已附上我的密碼。誰可以幫我這個事?

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title>Hotel Beds</title> 
<script type="text/javascript" 
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" 
></script> 
<script type="text/javascript"> 

    $(document).ready(function() { 
     var values = {}; 
     $('input:radio').change(function() { 
      var name = $(this).attr('name'); 
      values[name] = parseFloat($(this).data('price')); 
      var total = 0.0; 
      $.each(values, function(i, e) { 
       total += e; 
      }); 
      $('#total').text(total.toFixed(2)); 
     }); 
    });    
    </script> 
</head> 
<body> 
    <form id="form1"> 
    <div> 
     <input type="radio" name="t1" data-price="25" checked="checked" /> 
     <span>Price 25</span> 
     <input type="radio" name="t1" data-price="30" /> 
     <span>Price 30</span> 
     <br /> 
     <input type="radio" name="t2" data-price="40" /> 
     <span>Price 40</span> 
     <input type="radio" name="t2" data-price="50" /> 
     <span>Price 50</span> 
     <br /> 
     <input type="radio" name="G" /><span>Male</span> 
     <input type="radio" name="G" /><span>Female</span> 
     <input id="total" type="text" /> 
    </div> 
    </form> 
</body> 
</html> 

回答

2

我需要做一些計算,如果單選按鈕有數據價格屬性。

可以使用"has attribute" selector來限制選擇只與該屬性的單選按鈕:

$('input:radio[data-price]').change(... 

邊注:使用jQuery的CSS擴展是不是最好的做法,因爲as it says in the :radio API documentation,它意味着jQuery無法切換到瀏覽器的本地處理。相反:

$('input[type=radio][data-price]').change(... 
+0

7秒快,那麼不妨給予好評你的。 – adeneo

+0

@adeneo :-) ... –

1

我不得不改變一個想法來增加總數。

$(document).ready(function() { 

    var values = {}; 
    $('input:radio[data-price]').change(function(){ 

      var name = $(this).attr('name'); 
      values[name] = parseFloat($(this).data('price')); 
      var total = 0.0; 
      $.each(values, function (i, e) { 
      total += e; 
      console.log('total', total); 
      }); 
      $('#total').val(total.toFixed(2)); // val(total) instead of text(total) 
    }); 
}); 

請參閱working demo at plnkr.co

+0

好的。 ... –

相關問題