假设我有以下脚本,计算总和。
这是代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript">
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5;
}
</script>
</head>
<body>
<?php
$tR = 1;
$maxlines = 5;
echo '<form name="form" method="post" action="action.php">';
echo '<table><tbody>';
while($tR <= $maxlines)
{
echo '<tr>';
echo '<td width="1"><input name="price_' . $tR . '" onChange="updatesum();" type="text"></td>';
echo '<td width="1"> x </td>';
echo '<td width="1"><input name="number_' . $tR . '" onChange="updatesum();" type="text" value="1"></td>';
echo '</tr>';
++$tR;
}
echo '</tbody></table>';
echo 'Total: <input name="sum" value="0" type="text" readonly="readonly">';
echo '<button type="submit" name="Submit" style="display: hidden;">Submit</button>';
echo '</form>';
?>
</body>
</html>
没关系...但是现在我将变量 $maxlines 从 5 更改为 500...如何调整 Javascript,而无需编写类似的内容:
function updatesum() {
line1 = ((document.form.price_1.value -0) * (document.form.number_1.value -0));
line2 = ((document.form.price_2.value -0) * (document.form.number_2.value -0));
line3 = ((document.form.price_3.value -0) * (document.form.number_3.value -0));
line4 = ((document.form.price_4.value -0) * (document.form.number_4.value -0));
line5 = ((document.form.price_5.value -0) * (document.form.number_5.value -0));
line6 = ((document.form.price_6.value -0) * (document.form.number_6.value -0));
.......................
line500 = ((document.form.price_500.value -0) * (document.form.number_500.value -0));
document.form.sum.value = line1 + line2 + line3 + line4 + line5 + line6 ........... + line500;
}