减去两笔总和的结果

时间:2015-09-29 04:22:31

标签: javascript jquery

我试图减去两个总数。 我有一张收入表,最后一行是"总收入"和另一个费用表,最后一行是"总费用" 我需要添加另一个计算总收入减去总费用的函数。如果费用大于收入,我还需要显示负数。

我的问题是,我不太明白如何使用它存储在我之前的函数中的值,所以我可以在新的函数上重用它。我对javascript / jquery相当新,所以我很难理解文档。 任何有关这方面的指导都将非常感谢

这是js

    $(document).ready(function () {

    //iterate through each textboxes and add keyup
    //handler to trigger sum event
    $(".txtA").each(function () {
        $(this).keyup(function () {
            calculateSumA();
            calculateSubstraction();
        });
    });

});

function calculateSumA() {

    var sum = 0;
    //iterate through each textboxes and add the values
    $(".txtA").each(function () {
        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            sum += parseFloat(this.value);
        }

    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#sumA").html(sum.toFixed(2));
}

$(document).ready(function () {

    //iterate through each textboxes and add keyup
    //handler to trigger sum event
    $(".txt").each(function () {

        $(this).keyup(function () {
            calculateSum();
            calculateSubstraction();
        });
    });

});

function calculateSum() {

    var sum = 0;
    //iterate through each textboxes and add the values
    $(".txt").each(function () {
        //add only if the value is number
        if (!isNaN(this.value) && this.value.length != 0) {
            sum += parseFloat(this.value);
        }
    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#sum").html(sum.toFixed(2));
}


function calculateSubstraction() {
    var subs = calculateSum() - calculateSumA();
    $("#subs").html(subs.toFixed(2));

}

这是html

<body>
<table width="300px" border="1">
    <tr>
        <td width="40px">1</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>4</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>5</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>6</td>
        <td>income</td>
        <td>
            <input class="txtA" type="text" name="txt" />
        </td>
    </tr>
    <tr class="income">
        <td>&nbsp;</td>
        <td align="right">total income:</td>
        <td align="center"><span id="sumA">0</span>
        </td>
    </tr>
</table>
<br/>
<table width="300px" border="1">
    <tr>
        <td width="40px">1</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>4</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>5</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>6</td>
        <td>expense</td>
        <td>
            <input class="txt" type="text" name="txt" />
        </td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td align="right">total expenses:</td>
        <td align="center"><span id="sum">0</span>
        </td>
    </tr>
</table>
<br/>
<table width="300px" border="1">
    <tr>
        <td style="width:40px"></td>
        <td style="width:62px">Remaining:</td>
        <td align="center"><span id="su">0</span>
        </td>
    </tr>
</table>

http://jsfiddle.net/gnzLwzuy/5/ 我知道它可以被优化,因为我重复了太多的代码,但如果我改变它太多它停止工作。 (我有太多东西需要学习......)

6 个答案:

答案 0 :(得分:2)

只是为了补充Guruprasad的答案,并直接回应一个函数如何访问另一个函数计算的值

简单方法

1 - 声明全局变量并在函数中使用它们。

var foo;

function calculateSumA() {
  ....
  foo = some value;
}

function OtherFunc() {
  ....
  var localVar = foo;
}

2 - 使函数返回一个值并将其存储在其他函数可以访问的位置(例如全局变量);

不那么简单

您可以使用闭包来创建私人成员的幻觉。 我写了一篇关于JS闭包的文章。如果您对此感到好奇,我相信它会帮助您更好地理解这个概念:https://usonsci.wordpress.com/2014/10/04/closure-with-javascript/

答案 1 :(得分:1)

但是,您在每个calculateSubstraction的{​​{1}}上致电keyup,只需从每个textbox的{​​{1}}获取值,并相应地total如下:

section

<强> DEMO

<强>更新

以下是subtract的更优化版本。我更喜欢function calculateSubstraction() { var subs=parseFloat($("#sumA").text()) - parseFloat($("#sum").text()) $("#su").html(subs); } 事件而不是code,因为它更可靠地计算并减少每个blur上的事件触发

keyup

<强> Updated DEMO

答案 2 :(得分:0)

DEMO

您需要从添加功能中返回一个值,然后添加

return sum.toFixed(2);
return sum.toFixed(2);

来自两个函数并从减法函数中减去

var data = calculateSum();
var dataa = calculateSumA();
var subs = dataa-data;
$("#su").html(subs.toFixed(2));

答案 3 :(得分:0)

我已经为您的代码制作了纯Javascript版本,并添加了两个新功能:

  • 用于向incomeexpense表格动态添加新行的按钮。
  • 并删除用户在文本字段中添加除数字以外的任何内容的功能。

完整注释的代码如下:

&#13;
&#13;
/* when all elements of the page are available */
document.addEventListener('DOMContentLoaded', function() {
  /* get the tables income and expense, and the 'total' fields */
  var income = document.getElementById('income'),
      expense = document.getElementById('expense'),
      totalIncome = document.getElementById('totalIncome'),
      totalExpense = document.getElementById('totalExpense'),
      total = document.getElementById('total');

  /* create the calculate function */
  function calculate(e) {
    /* get all the textfields of each table */
    var incomes = [].slice.call(income.querySelectorAll('input')),
        expenses = [].slice.call(expense.querySelectorAll('input'));

    /* calculate the sum of the fields by using
       - map to convert the values to numbers
       - and reduce to sum those values */
    var sumIncome = incomes.map(function(el) {
      /* don't allow users to input other values than numbers */
      el.value = el.value.replace(/[^0-9\.]/g, '');
      return Number(el.value);
    }).reduce(function(a, b) {
      return a + b;
    });

    var sumExpense = expenses.map(function(el) {
      /* don't allow users to input other values than numbers */
      el.value = el.value.replace(/[^0-9\.]/g, '');
      return Number(el.value);
    }).reduce(function(a, b) {
      return a + b;
    });
    
    /* change the totalIncome and totalExpense labels */
    totalIncome.textContent = sumIncome;
    totalExpense.textContent = sumExpense;

    /* change the total remaining label */
    total.textContent = sumIncome - sumExpense;
  }
  
  /* add the event handlers to the oninput event to both tables
     they will call the calculate function above when they happen */
  income.addEventListener('input', calculate);
  expense.addEventListener('input', calculate);

  /* this is a bonus, I've added 'new' buttons to dynamically add more rows */
  document.addEventListener('click', function(e) {
    var el = e.target;

    if (el.className === 'new') {
      var table = el.parentNode.parentNode.parentNode,
        tr = document.createElement('tr');

      tr.innerHTML = '<td>' + [].slice.call(table.querySelectorAll('tr')).length + '</td>\
                      <td>income</td>\
                      <td>\
                        <input class="txtA" type="text" />\
                      </td>';
      table.insertBefore(tr, el.parentNode.parentNode);
    }
  });
});
&#13;
body {
  font-family: sans-serif;
}
table {
  border-collapse: collapse;
  border-color: white;
  background-color: powderblue;
}
.txt,
.txtA {
  background-color: #FEFFB0;
  font-weight: bold;
  text-align: right;
}
&#13;
<table id='income' width="300px" border="1">
  <tr>
    <td width="40px">1</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>2</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>3</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>4</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>5</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>6</td>
    <td>income</td>
    <td>
      <input class="txtA" type="text" name="txt" />
    </td>
  </tr>
  <tr class="income">
    <td>
      <button class="new">new</button>
    </td>
    <td align="right">total income:</td>
    <td align="center"><span id="totalIncome">0</span>
    </td>
  </tr>
</table>
<br/>
<table id='expense' width="300px" border="1">
  <tr>
    <td width="40px">1</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>2</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>3</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>4</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>5</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>6</td>
    <td>expense</td>
    <td>
      <input class="txt" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>
      <button class="new">new</button>
    </td>
    <td align="right">total expenses:</td>
    <td align="center"><span id="totalExpense">0</span>
    </td>
  </tr>
</table>
<br/>
<table width="300px" border="1">
  <tr>
    <td style="width:40px"></td>
    <td style="width:62px">Remaining:</td>
    <td align="center"><span id="total">0</span>
    </td>
  </tr>
</table>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

用这个替换你的calculateSubstraction()函数:

&#13;
&#13;
function calculateSubstraction() {
var Income =  parseFloat($('#sumA').html());
var Expense =  parseFloat($('#sum').html());
var subs = Income - Expense;
$("#su").html(subs.toFixed(2));

}
&#13;
&#13;
&#13;

答案 5 :(得分:0)

使用jQuery,您可以进行简单的计算,例如

jQuery(function() {
  var sum = {
    income: 0,
    deduction: 0
  };
  $('input.entry').keyup(function() {
    var $table = $(this).closest('table'),
      total = 0;
    $table.find('input.entry').each(function() {
      total += +this.value || 0;
    });
    $table.find('span.total').html(total)
    sum[$table.data('type')] = total;
    $('#su').html(sum.income - sum.deduction);
  })
})
 body {
   font-family: sans-serif;
 }
 table {
   border-collapse: collapse;
   border-color: white;
   background-color: powderblue;
 }
 input.entry {
   background-color: #FEFFB0;
   font-weight: bold;
   text-align: right;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300px" border="1" class="entry" data-type="income">
  <tr>
    <td width="40px">1</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>2</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>3</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>4</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>5</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>6</td>
    <td>income</td>
    <td>
      <input class="txtA entry" type="text" name="txt" />
    </td>
  </tr>
  <tr class="income">
    <td>&nbsp;</td>
    <td align="right">total income:</td>
    <td align="center"><span class="total">0</span>
    </td>
  </tr>
</table>
<br/>
<table width="300px" border="1" class="entry" data-type="deduction">
  <tr>
    <td width="40px">1</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>2</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>3</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>4</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>5</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>6</td>
    <td>expense</td>
    <td>
      <input class="txt entry" type="text" name="txt" />
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td align="right">total expenses:</td>
    <td align="center"><span class="total">0</span></td>
  </tr>
</table>
<br/>
<table width="300px" border="1">
  <tr>
    <td style="width:40px"></td>
    <td style="width:62px">Remaining:</td>
    <td align="center"><span id="su">0</span>
    </td>
  </tr>
</table>