我一直试图制作一个等级预测器一段时间,每当我放入这些输入框并让函数运行变量时它就不起作用。我使用原来的四个输入,但我想添加更多。我复制并粘贴了所有框和代码以及脚本部分的代码,但我更改了所有数字,所以我可以有10个框。我按下了按钮,我的警报没有弹出。
<script type="text/javascript">
function notEmpty()
{
var grade1 = $('#g1').val().trim();
var weight1 = $('#w1').val().trim();
var grade2 = $('#g2').val().trim();
var weight2 = $('#w2').val().trim();
var grade3 = $('#g3').val().trim();
var weight3 = $('#w3').val().trim();
var grade4 = $('#g4').val().trim();
var weight4 = $('#w4').val().trim();
var total = 0;
var count = 0;
if (grade1.length > 0 && weight1.length > 0)
{
$("#t1").text(grade1 * weight1);
total += (grade1 * weight1);
count += parseInt(weight1);
}
if (grade2.length > 0 && weight2.length > 0)
{
$("#t2").text(grade2 * weight2);
total += (grade2 * weight2);
count += parseInt(weight2);
}
if (grade3.length > 0 && weight3.length > 0)
{
$("#t3").text(grade3 * weight3);
total += (grade3 * weight3);
count += parseInt(weight3);
}
if (grade4.length > 0 && weight4.length > 0)
{
$("#t4").text(grade4 * weight4);
total += (grade4 * weight4);
count += parseInt(weight4);
}
var grandTotal = total / count;
alert grandTotal;
}
</script>
<h2>Grade Predictor</h2>
<p>Enter your grade (4, 3, 2, 1, or 0) into the grade slots. Enter the weight (5, 4, 3, 2, or 1) into the weight slots. Hit Calculate Grades to show your current grade.</p>
<div>
<label for="g1">Grade:</label><input type="number" id="g1" name="grade1">
<label for="w1">Weight:</label><input type="number" id="w1" name="weight1">
<label id="t1">
</div>
<div>
<label for="g2">Grade:</label><input type="number" id="g2" name="grade2">
<label for="w2">Weight:</label><input type="number" id="w2" name="weight2">
<label id="t2">
</div>
<div>
<label for="g3">Grade:</label><input type="number" id="g3" name="grade3">
<label for="w3">Weight:</label><input type="number" id="w3" name="weight3">
<label id="t3">
</div>
<div>
<label for="g4">Grade:</label><input type="number" id="g4" name="grade4">
<label for="w4">Weight:</label><input type="number" id="w4" name="weight4">
<label id="t4">
</div>
<p>
<input type='button' onclick='notEmpty()' value='Calculate Grades'/>
</p>
我为其他6个盒子添加了代码,当我删除了与这些输入有关的脚本,变量,函数和Div时,我打破了它。
任何帮助都将不胜感激 - 我对编程很陌生。
提前致谢!
编辑:如果您需要我的代码的其他部分,您可以拥有它 - 只需要问。如果它有帮助,它将内置到HTML文档中。
答案 0 :(得分:1)
问题是
alert grandTotal;
由于alert
是一个函数,您应该使用
alert(grandTotal);
无论如何,您可以使用数组和循环来简化代码:
function notEmpty() {
var grades = [], weights = [],
total = 0, count = 0;
for(var i=1; i<=4; ++i) {
grades[i] = $('#g'+i).val().trim();
weights[i] = $('#w1'+i).val().trim();
if (grades[i].length > 0 && weights[i].length > 0) {
$("#t"+i).text(grades[i] * weights[i]);
total += grades[i] * weights[i];
count += parseInt(weights[i]);
}
}
var grandTotal = total / count;
alert(grandTotal);
}