我的页面上有多个链接,当您单击时,会有一个 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
主对象内的每个“问题”对象的属性questionsObjectData
都是未定义的。无论问题是否有文本标签或单选按钮,如果文本标签为空或未选中单选按钮,总是undefined
为什么会这样?我需要提供 HTML 代码吗?