输入文本/无线电的Jquery值未定义

时间:2013-04-23 20:19:17

标签: javascript jquery html object undefined

我的页面上有多个链接,当您点击时,会显示一个div,根据您点击的链接显示测验。测验使用ajax显示。测验由多个div组成,如下所示:

<div class="displayquiz-particularquestion-container1" > ... </div>
<div class="displayquiz-particularquestion-container2" > ... </div>
...................................................................
<div class="displayquiz-particularquestion-containern" > ... </div>

其中n是问题的总数,因此是div的总数。每个div包含一个文本形式的问题,为了回答问题,每个div包含一个文本输入标记或多个单选按钮。您可以在具有输入标签的答案上写下答案,并使用单选按钮检查答案。

现在,我希望能够循环遍历所有这些div(这就是为什么我给它们提供了唯一的类名)并检查它们是否包含文本输入标记或单选按钮,并获取文本输入标记的值或分别检查单选按钮的值。

到目前为止,我的代码看起来像这样。注意:check-answers-button是用户按下以在测验中检查其答案的按钮标记的ID。基本上所有问题都已显示,用户回答了问题,所以现在我需要找出答案。此外,displayTo对象代表主div,其中包含所有包含问题的div。

$(document).on('click','#check-answers-button',function(evt){
    evt.preventDefault();

    // ------ Get the class of the last question container and extract the number from it so as to know how
    //           many questions to loop through

    var numberOfQuestionsClass = displayTo.find('[class*="displayquiz-particularquestion-container"]:last').attr('class');
    var numberOfQuestions = '';

    for(var y = numberOfQuestionsClass.length - 1 ; y > 0; y-- )
        if(!isNaN(numberOfQuestionsClass[y])) numberOfQuestions += numberOfQuestionsClass[y];
        else break;

    // ------ The 'numberOfQuestions' variable now contains the number of questions

    // ------ 'questionsObjectData' will contain all the questions and thier respective answers
    questionsObjectData = {};

    // ------ Loop through all the questions and get the answers
    for(x = 1; x <= numberOfQuestions; x++){
        var question = displayTo.find('.displayquiz-particularquestion-container' + x);


        questionsObjectData['question' + x] = {};

        // ------ Check if the question has a written answer
        if(question.find('input[name=written-answer]').val() === undefined){

            // ------ The question is an option question, get the checked radio button and add it
            //           to the 'questionsObjectData' object

            questionsObjectData['question' + x]['answer'] = question.find('input[name=written-answer]').val();

        }else{

            // ------ The question has a written answer, get the content of the input text field and add it
            //           to the 'questionsObjectData' object

            questionsObjectData['question' + x]['answer'] = question.find('input[type="radio"]:checked').val();

        }
    }

    console.log(questionsObjectData);

});

到目前为止,我使用console.log(questionsObjectData);来查看我的数据内容。问题是主answer对象中每个'question'对象的questionsObjectData属性都是未定义的。无论问题是文本标签还是单选按钮,如果文本标签为空或未选中单选按钮,它始终是undefined为什么?我是否需要提供HTML代码?

0 个答案:

没有答案