使用jQuery迭代json数据时,编号是相反的

时间:2014-12-29 12:43:57

标签: jquery json html5

我有一个jQuery each函数,它返回一个记录列表。数据是测验问题和答案,我需要对问题进行编号。但令我惊讶的是,编号从最后开始。以下是我的代码:

var html;
var pno = 0;
$.each(data.results, function (i, r) {
    pno += 1;

    html = '<div class="questions"><h3 class="quest">' + pno + '&nbsp;' +
        r.QuestionText + '</h3><ul>';

    $.each(r.Answers, function (i, ans) {
        html += '<li>' + ans.AnswerLabel + '&nbsp;<input type="radio" data-question="' + ans.QuestionId + '" name="answer" value="' + ans.AnswerId + '"/>' + ans.AnswerText + '</li>';
    });

    html += '</ul><input type="submit" style="float:left"  value="Previous" class="orange-button prev">' +
    '<input type="submit" value="Next >>" class="orange-button next"></div>'
    $(".dummy").after(html);
});

pno变量应该是问题编号。

2 个答案:

答案 0 :(得分:2)

在外部$.each循环之外的变量中缓存问题并回答DIV,并在$.each循环后立即插入html。此外,最好一次修改DOM元素而不是循环内部。

var html;
var pno = 0;
var qWithA='';
$.each(data.results, function (i, r) {
    pno += 1;

    html = '<div class="questions"><h3 class="quest">' + pno + '&nbsp;' +
        r.QuestionText + '</h3><ul>';

    $.each(r.Answers, function (i, ans) {
        html += '<li>' + ans.AnswerLabel + '&nbsp;<input type="radio" data-question="' + ans.QuestionId + '" name="answer" value="' + ans.AnswerId + '"/>' + ans.AnswerText + '</li>';
    });

    html += '</ul><input type="submit" style="float:left"  value="Previous" class="orange-button prev">' +
    '<input type="submit" value="Next >>" class="orange-button next"></div>'
    qWithA += html;
});
$(".dummy").after(qWithA);

答案 1 :(得分:0)

您可能将afterappend混为一谈。使用后者将按预期工作:

var data = { 
    results: [
        {
            QuestionText: 'Coffee?', 
            Answers: [
                {AnswerLabel: 'Yes', AnswerId: 1},
                {AnswerLabel: 'No', AnswerId: 2}
            ]
        },{
            QuestionText: 'Tea?', 
            Answers: [
                {AnswerLabel: 'Yes', AnswerId: 3},
                {AnswerLabel: 'No', AnswerId: 4}
            ]
        }
    ]
};
    
var html;
var pno = 0;
$.each(data.results, function (i, r) {
    pno += 1;

    html = '<div class="questions"><h3 class="quest">' + pno + '&nbsp;' +
        r.QuestionText + '</h3><ul>';

    $.each(r.Answers, function (i, ans) {
        html += '<li>' + ans.AnswerLabel + '&nbsp;<input type="radio" data-question="' + ans.QuestionId + '" name="answer" value="' + ans.AnswerId + '"/>' + ans.AnswerText + '</li>';
    });

    html += '</ul><input type="submit" style="float:left"  value="Previous" class="orange-button prev">' +
    '<input type="submit" value="Next >>" class="orange-button next"></div>'
    $(".dummy").append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dummy"></div>