重构我的coffescript代码以获得特定列值的总和

Refactoring my coffeescript code to get sum of particular columns values

本文关键字:coffescript 我的 代码 重构      更新时间:2023-09-26

这可能是个小问题,但我是coffeescript和javascript的新手,我正试图弄清楚如何重构下面的代码,以获得具有不同类名的两列的值的总和,并将其显示在我的html页面中。以下是迄今为止我得到的代码:

totalItems = ->
  column= $("#websiteTable td[class=website_count]")
  theTotal = 0
  column.each ->
    value = $(this).html()
    theTotal += parseInt(value)
    return
  alert(theTotal)
newItems = ->
  column= $("#websiteTable td[class=new_count]")
  theTotal = 0
  column.each ->
    value = $(this).html()
    theTotal += parseInt(value)
    return
  alert(theTotal)

正如你所看到的,有很多重复的代码,我该如何有效地重写?

感谢

创建一个以jQuery选择器为参数的函数。
calculateTotal = (element, total = 0) ->
    element.each ->
        value = $(@).html()
        total += +value
    total

然后你可以做:

totalItems = calculateTotal $ "#websiteTable td[class=website_count]"
newItems = calculateTotal $ "#websiteTable td[class=new_count]"

请参阅下面的实际示例。

var calculateTotal;
calculateTotal = function(element, total) {
  if (total == null) {
    total = 0;
  }
  element.each(function() {
    var value;
    value = $(this).html();
    return total += +value;
  });
  
  return total;
};
$('button').on('click', function(){
	alert(calculateTotal($('ul li')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li>2</li>
  	<li>4</li>
</ul>
<button>Calculate the total</button>