2011-06-05 181 views
0

我有一個函數需要從每個輸入中總結出來,但同時每個輸入都必須顯示百分比。我找到了總結價值的方法,但我有問題顯示百分比。下面是HTML代碼:jquery - 計算每個值的百分比

Price 1: <input type="text" name="price01" class="price" /> 
Percentage 1: <span class='p'></span> 
<br/> 
Price 2: <input type="text" name="price02" class="price" /> 
Percentage 2: <span class='p'></span> 
<br/> 
Price 3: <input type="text" name="price03" class="price" /> 
Percentage 3: <span class='p'></span> 
<br/> 
Price 4: <input type="text" name="price04" class="price" /> 
Percentage 4: <span class='p'></span> 
<br/> 
Total: <span class="total"></span> 

jQuery代碼我在互聯網上找到:

$.fn.sumValues = function() { 
    var sum = 0; 
    this.each(function() { 
     if ($(this).is(':input')) { 
      var val = $(this).val(); 
     } else { 
      var val = $(this).text(); 
     } 
     sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10); 
    }); 
    return sum; 
}; 

$(document).ready(function() { 
    $('input.price').bind('keyup', function() { 
     $('span.total').html($('input.price').sumValues()); 
    }); 
}); 

希望任何人都可以幫助...謝謝你。


謝謝,夥計們。我想我已經解決了這個問題。這可能不是最好的解決方案,但我明白了它的實現方法。再次謝謝:)

解決方案代碼:http://jsfiddle.net/amaleen123/6jnKf/2/

回答

0

我不知道的JavaScript語法時才所以我的答案可能不是太大的幫助,但你應該需要做的是,你計算出總/總和之後,將每個數值除以將給出百分比並將該數值放在適當範圍內的總數。

希望即使沒有任何實際的代碼,也可以提供幫助。

+0

非常感謝,科裏。我有這個想法。非常感謝:) – lina83 2011-06-05 07:57:50

0

這工作

$(document).ready(function() { 

    var $prices = $('input.price'); 

    $prices.bind('keyup', function() { 
     var sum = $prices.sumValues(); 
     $('span.total').html(sum); 

     $('.p').each(function(i,e){ 
      $(e).text($prices.eq(i).val()/sum); 
     }); 
    }); 
}); 

基本上每個thime keyUp事件被觸發並sumValues被調用後,您需要再次遍歷這些元素來計算百分比分別。

這絕不是最有效的解決方案,但它可以在您完善工作的同時完成工作。

+0

我明白了。現在我明白了。謝謝,吉姆:) – lina83 2011-06-05 07:59:33