编写这个jQuery的更好方法

时间:2014-02-05 10:47:27

标签: jquery performance

我怎么能重新编写这段代码才能更干? 我只是对此进行了调整并对其进行了扩展,但显然会有更好的方式来编写它。只是不确定如何?

incomeSum();
expenseSum();
debtSum();
savingsSum();
billsSum();

function incomeSum() {
    var sum=0;
    //iterate through each input and add to sum
    $('#income .amount').each(function() {     
            sum += parseInt($(this).text());                     
    }); 
    //change value of total
    $('#income .total').html('$'+sum);
}
function expenseSum() {
    var sum=0;
    //iterate through each input and add to sum
    $('#expense .amount').each(function() {     
            sum += parseInt($(this).text());                     
    }); 
    //change value of total
    $('#expense .total').html('$'+sum);
} 

etc etc ....

2 个答案:

答案 0 :(得分:2)

一种方法是将选择器作为函数的参数提供:

function sum(inputSelector, outputSelector) {
    var sum=0;
    //iterate through each input and add to sum
    $(inputSelector).each(function() {     
            sum += parseInt($(this).text());                     
    }); 
    //change value of total
    $(ouputSelector).html('$'+sum);
} 

<强>用法

sum("#expense .amount", "#expense .total");

另一种方法是将jQuery对象作为参数传递:

function sum($inputs, $output) {
    var sum=0;
    //iterate through each input and add to sum
    $inputs.each(function() {     
            sum += parseInt($(this).text());                     
    }); 
    //change value of total
    $output.html('$'+sum);
} 

<强>用法

sum($('#expense .amount'), $('#expense .total'));

答案 1 :(得分:0)

function awesomeSum(id) {
    var sum=0;
    $(id).find('.amount').each(function() {     
            sum += parseInt($(this).text());                     
    }); 
    //change value of total
    $(id).find('.total').html('$'+sum);
}

然后:

$.each(['#income', '#expense', '#debt', '#bills'], function(){

  awesomeSum(this);

});