我仍然对javascript很陌生,并且想知道是否有更有效的方法来处理这种情况,例如使用数组?
我有一个包含6个字段的HTML表单,可让您输入最近六周的加班费。然后我使用javascript将六个值加起来,除以6并乘以52得到年度加班金额。我的字段名为w_ot_1,w_ot_2至w_ot_6,我使用下面的代码。这一切都很好,但我发现它真的很重复,而且不仅仅是加班我需要运行这个计算。我确信这是一种更有效的方法。有没有人有任何想法可以提供帮助?
var weekly_ot_1 = parseFloat(document.getElementById("w_ot_1").value.replace(/[^0-9.]/g, ''));
var weekly_ot_2 = parseFloat(document.getElementById("w_ot_2").value.replace(/[^0-9.]/g, ''));
var weekly_ot_3 = parseFloat(document.getElementById("w_ot_3").value.replace(/[^0-9.]/g, ''));
var weekly_ot_4 = parseFloat(document.getElementById("w_ot_4").value.replace(/[^0-9.]/g, ''));
var weekly_ot_5 = parseFloat(document.getElementById("w_ot_5").value.replace(/[^0-9.]/g, ''));
var weekly_ot_6 = parseFloat(document.getElementById("w_ot_6").value.replace(/[^0-9.]/g, ''));
//weekly annualised overtime values
document.getElementById("w_annual_ot").value= addCommas((((weekly_ot_1 + weekly_ot_2 + weekly_ot_3 + weekly_ot_4 + weekly_ot_5 + weekly_ot_6)/6) * 52).toFixed(2));
答案 0 :(得分:2)
在调用for
时,您可以利用简单的document.getElementById()
循环和字符串连接。我建议创建一个函数来计算已支付的加班时间并让函数将周数作为参数,以便在添加更多字段时可以轻松更改它。
function getOvertimePaid(numberOfWeeks) {
var total = 0;
// Iterate from 1 to the number of weeks and increment the total by
// the parsed value in the field for the current index
for (var i=1; i<=numberOfWeeks; i++) {
total += parseFloat(document.getElementById('w_ot_' + i).value.replace(/[^0-9.]/g, '');
}
// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}
// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getOvertimePaid(6).toFixed(2));
您可能希望了解的另一件事是使代码和支持HTML更加灵活,就是在每周加班输入元素上使用类名。如果您这样做并稍微调整代码,您可以随意添加或删除字段,并且计算年度加班的功能将继续有效。举个例子:
<强> HTML 强>
<input type="text" id="w_ot_1" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_2" class="weekly-overtime" value="0.00" />
<input type="text" id="w_ot_3" class="weekly-overtime" value="0.00" />
<强>的JavaScript 强>
function getAnnualizedValue(className) {
// Get all elements with the given class name
var elements = document.getElementsByClassName(className);
// Iterate the elements and keep a running total of their values
var total = 0;
for (var i = 0; i < elements.length; i++) {
total += parseFloat((elements[i].value || '0').replace(/[^0-9.]/g, '');
}
// Return the annualized amount as a float for flexibility
return (total / numberOfWeeks) * 52;
}
// Update weekly annualised overtime values and provide formatting at this point
document.getElementById("w_annual_ot").value= addCommas(getAnnualizedValue('weekly-overtime').toFixed(2));