编写此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 :-)