我已嵌套for循环。第一个是从XML文件中获取问题和答案,内部循环是添加属于头部问题的子问题...... 我的代码:
for (var i = 0 ; i < size; i++) {
var question = xml.find('row').eq(i).find('question').text();
var sizeQ = xml.find('row').eq(i).find('question_down').size();
var answer = xml.find('row').eq(i).find('answer').text
$('.faq_row').append(" <div class='faq_details'> <li class='faq_quest' > <a class='faq_row_question'>" + question +
"<div class='faq_triangle_down'> </div></a> <div class='faq_inside_question'> <p class='faq_answer'>" + answer + "</p> <div class='faq_sub_questions'> </div> </div> </li> </div> <br>"); //here i get question and answer for the question
for (var j = 0; j < sizeQ; j++) {
var subquestion = xml.find('row').eq(i).find('question_down').eq(j).text();
$('.faq_sub_questions').append("<a class = 'faq_sub_question_link'>" + subquestion + "</a> <br class='faq_br'>"); // here i get all sub questions
}
}
我的问题是所有子问题写入同一个类“faq_sub_questions”,在第一个问题中,我看到XML文件中的所有子问题, 我想为每个问题添加自己的子问题... 有什么建议吗?
答案 0 :(得分:1)
尝试将faq_details
元素存储在变量中,然后使用此变量使用faq_sub_questions
方法替换当前行find
div,最后附加divs链接faq_sub_question_link
:
//Store your faq_details in variable
var faq_details = $(" <div class='faq_details'> <li c.....");
$('.faq_row').append( faq_details );
//Then use this variable to targer the current row
faq_details.find('.faq_sub_questions').append("<a class = 'faq_sub_question_link'>...
希望这有帮助。
答案 1 :(得分:1)
您可以每次创建并引用新的父元素:
for (var i = 0 ; i < size; i++) {
var question = xml.find('row').eq(i).find('question').text();
var sizeQ = xml.find('row').eq(i).find('question_down').size();
var answer = xml.find('row').eq(i).find('answer').text
// here define `parenter` variable
var parenter = $(" <div class='faq_details'> <li class='faq_quest' > <a class='faq_row_question'>" + question +
"<div class='faq_triangle_down'> </div></a> <div class='faq_inside_question'> <p class='faq_answer'>" + answer + "</p> <div class='faq_sub_questions'> </div> </div> </li> </div> <br>");
// here append using the new variable name
$('.faq_row').append( parenter ); //here i get question and answer for the question
for (var j = 0; j < sizeQ; j++) {
var subquestion = xml.find('row').eq(i).find('question_down').eq(j).text();
// here again append to new parent variable instead
parenter.children(".faq_sub_questions").append("<a class = 'faq_sub_question_link'>" + subquestion + "</a> <br class='faq_br'>"); // here i get all sub questions
}
}