我正在设计一个 JavaScript 函数checkForm(),用于检查表单的至少一半答案是否已完成。如果满足条件,则返回“true”,否则返回警报消息,否则返回“false”。答案在输入文本字段中给出,其内容不能是空字符串才能被视为已回答。
为了进行检查,函数checkForm()调用另外两个函数: totalNumberOfQuestions( )和totalCompletedAnswers(),如下所示:
function totalNumberOfQuestions() /* Returns the total number of questions in the form */
{ total
numberOfQuestions = 0;
i = 1;
do
{
nameOfAnswer = 'answer_' + i;
if(document.getElementsByName(nameOfAnswer)[0] != null)
{
totalnumberOfQuestions ++;
}
i++;
}
while (document.getElementsByName(nameOfAnswer)[0] != null);
return totalnumberOfQuestions;
}
function totalCompletedAnswers() /* Returns the total number of completed answers in the form */
{
numberOfCompletedAnswers = 0;
i = 1;
for(i = 1; i<= totalNumberOfQuestions(); i++)
{
nameOfAnswer = 'answer_' + i;
if ( form[nameOfAnswer].value != '')
{
numberOfCompletedAnswers ++;
}
}
return numberOfCompletedAnswers;
}
function checkForm()
{
if ( totalCompletedAnswers() < 7 )
{
alert("Please answer at least half of the questions.");
return false;
}
return true;
}
但是,令人惊讶的是,函数checkForm()在这种形式下不能正常工作,即使完成的答案数量少于答案总数的一半,它也会返回 true。但是,如果根据常量值检查函数totalCompletedAnswers(),则该函数可以正常工作,例如:
function checkForm()
{
if ( totalCompletedAnswers() < 7 )
{
alert("Please answer at least half of the questions.");
return false;
}
return true;
}
这意味着在checkForm()函数的主体中使用函数totalNumberOfQuestions() 会“导入”一些不需要的返回值。即使我单独调用前者(x= totalNumberOfQuestions()然后重写条件:if ( totalCompletedAnswers() < x ) )也会发生这种情况。有谁知道在调用函数时如何避免这种不需要的返回值?