2011-06-05 140 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