Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编写此jQuery的更好方法_Jquery_Performance - Fatal编程技术网

编写此jQuery的更好方法

编写此jQuery的更好方法,jquery,performance,Jquery,Performance,如何重新编写此代码以使其更加枯燥? 我只是简单地修改并扩展了它,但显然会有更好的方法来编写它。只是不知道怎么做 incomeSum(); expenseSum(); debtSum(); savingsSum(); billsSum(); function incomeSum() { var sum=0; //iterate through each input and add to sum $('#income .amount').each(function() {

如何重新编写此代码以使其更加枯燥? 我只是简单地修改并扩展了它,但显然会有更好的方法来编写它。只是不知道怎么做

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 ....
然后:

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

  awesomeSum(this);

});

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

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");
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");
sum($('#expense .amount'), $('#expense .total'));

我不知道,但要求so重写jQuery两次似乎有点不合适。也许谷歌的东西之前和尝试的东西+1提供了一系列的选择(虽然我个人更喜欢第二)!1 :-)