-3

我正在设计一个 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 ) )也会发生这种情况。有谁知道在调用函数时如何避免这种不需​​要的返回值?

4

1 回答 1

0

totalComletedAnswers你有片段:

if(numberOfCompletedAnswers  < totalNumberOfQuestions() )
{
      alert("Please answer at least half of the questions.");
      return false;
}

所以如果所有答案都没有完成而不是totalCompletedAnswers回答的问题数量,那么将返回 false 。

checkForm以下将评估为真:false < 7

见:http: //jsfiddle.net/5mURZ/

看看这两篇文章,了解更多关于 javascript 中真实性/虚假性的信息:

更新

仔细检查后,您会遇到范围界定问题。你所有的变量都有一个全局范围。这将导致变量出现最多的问题ivar使用关键字声明变量会将变量的范围限制为函数。javascript 中的最佳实践是使用关键字对所有变量进行 devare ,var以显式声明变量的范围。

工作小提琴:http: //jsfiddle.net/Dr5Hx/1/

关于范围界定的文章:http: //coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

更新 2

对于完全不同的方法,试试jQuery的魔力。这种方法依赖于将答案包装在某种容器中。在这种情况下,一个div. 这是必需的,因为复选框和单选按钮等元素将是多个元素,但每个集合只应计算一次。

//The selector below finds DOM elements  with a name beginning with "answer"
var answers = $("[name^='answer']"); //'Cache' answers
var answerDivs = $("div").has("[name^='answer']"); //'Cache' answer divs
var totalAnswers =  answerDivs.length; //'Cache' number of answers

$("#checkIt").click(function(){ //Add a click listener to the button
    var numAnswered = $(answerDivs).filter(function(){ //Filter our answer divs to answered question
    var answer = $(this).find("[name^='answer']");  //Get the answer element(s) in the div
    var textCheck = $(answer).is("input:text") && $(answer).val() != ''; //Check For Text Value
    var selCheck = $(answer).is("select") && $(answer).val() != ''; //Check for selected 
    var radioCheck = $(answer).is(":checked"); // Check for Checked, WOrks for radio & checkbox
    //console.log($(answer).attr("name") + "  " + textCheck + " " + selCheck + " " + radioCheck)
    return (textCheck || selCheck || radioCheck); //End of the filter
    }).length;

    if(numAnswered < (totalAnswers/2))
    {
        alert("Please answer atleast half the questions");
        return false;
    }

    alert("We're good to go");
    return true;

});

只需确保将上述内容包裹在$(document).ready();

http://jsfiddle.net/Dr5Hx/3/

于 2013-04-24T00:44:13.297 回答