2013-04-02 134 views
0

我有一個功能,它目前加起來收到的折扣。我想將輸入的總和更改爲每個輸入的平均值javascript得到輸入的平均值

function calculateAverageDiscount() { 
    var avediscount = 0; 
    $("table.authors-list").find('input[name^="discount"]').each(function() { 
     avediscount += +$(this).val(); 
    }); 
    $("#avediscount").text(avediscount.toFixed(2)); 
} 

任何幫助讚賞。

回答

2

先取得你的元素列表:

var $disc = $("table.authors-list").find('input[name^="discount"]'); 

然後取它的長度:

var n = $disc.length; 

再取之,有你在,但使用先前獲得的列表,以便您不要重複自己

$disc.each(function() { 
    ... 
}); 

剩下的應該是顯而易見的... ;-)

+0

謝謝Alnitak, – Smudger

1

你需要獲得元素的數量,然後由這個數字除以總和。

var avediscount = 0; 
var length = $("table.authors-list").find('input[name^="discount"]').each(function() { 
    avediscount += +$(this).val(); 
}).length; 
$("#avediscount").text(avediscount.toFixed(2)/length); 
+1

謝謝vdua,作品100%! – Smudger