作为您选择的答案的替代方案,请考虑使用可用的集合并使用属性访问而不是函数调用。例如
<script>
// Test that v is an integer
function isInt(v) {
return /^\d+$/.test(v + '');
}
// Update the total if entered value is an integer
function updateTotal(e) {
var e = e || window.event;
var el = e.target || e.srcElement;
var value = el.value;
// If value is an integer, use it
if (isInt(value)) {
el.form.total.value = +el.form.total.value + +value;
// Otherwise, do nothing (or show an error message asking
// the user to input a valid value)
} else {
e.preventDefault();
}
return false;
}
// Add listeners to elements that need them
window.onload = function() {
var form = document.forms['f0'];
var els = form.elements;
var re = /^week/;
var total = 0;
for (var i=0, iLen=els.length; i<iLen; i++) {
if (re.test(els[i].name)) {
els[i].onchange = updateTotal;
}
}
}
</script>
<form id="f0" action="">
week1<input name="week1" value="0"><br>
week2<input name="week2" value="0"><br>
week3<input name="week3" value="0"><br>
week4<input name="week4" value="0"><br>
week5<input name="week5" value="0"><br>
total<input name="total" value="0" readonly>
<input type="reset"><input type="submit">
</form>
该isInt
函数有点简单,它应该修剪前导和尾随空格等,但足以表明您必须在操作中使用输入之前对其进行测试。这也是一个很好的例子,说明内联侦听器可能是更好的解决方案。