jquery增加1

时间:2012-07-23 13:43:08

标签: javascript jquery

下午,

对于每个显示的问题,我想将此代码中的数字增加1。

 new_question = "<div id=\"" + res.qId + "\">" +
                            "<h1>Question 1</h1>" +
                            "<p><i>" + res.question + "</i></p>" +
                            "<div class=\"answer-grid\">" +
                            "<div id=\"a1\" class=\"answer\">" +
                            "<p>" + res.answer1 + "</p>" +
                            "<p>" + res.answer2 + "</p>" +
                            "<p>" + res.answer3 + "</p>" +
                            "</div>" +
                            "</div>";

这将显示,问题1,问题2,依此类推......

请问如何在jQuery中执行此操作?

更新 Victor提供了我需要的东西,感谢所有人的帮助。更新了以下代码。

 var questionNumber = 1;
    $.each(result, function (index, res) {
        new_question = "<div id=\"" + res.qId + "\">" +
                        "<h1>Question " + (questionNumber++) + "</h1>" +
                        "<p><i>" + res.question + "</i></p>" +
                        "<div class=\"answer-grid\">" +
                        "<div id=\"a1\" class=\"answer\">" +
                        "<p>" + res.answer1 + "</p>" +
                        "<p>" + res.answer2 + "</p>" +
                        "<p>" + res.answer3 + "</p>" +
                        "</div>" +
                        "</div>";

        $('#pinfos').append(new_question);

2 个答案:

答案 0 :(得分:0)

声明一个名为questionNumber的var,并在每次调用时递增它

var questionNumber = 1;
        $.each(result, function (index, res) {
            new_question = "<div id=\"" + res.qId + "\">" +
                            "<h1>Question " + (questionNumber++) + "</h1>" +
                            "<p><i>" + res.question + "</i></p>" +
                            "<div class=\"answer-grid\">" +
                            "<div id=\"a1\" class=\"answer\">" +
                            "<p>" + res.answer1 + "</p>" +
                            "<p>" + res.answer2 + "</p>" +
                            "<p>" + res.answer3 + "</p>" +
                            "</div>" +
                            "</div>";

            $('#pinfos').append(new_question);

答案 1 :(得分:0)

在循环外声明一个变量并在循环内增加它并在标记中使用它。

var questionNumber=0;

$.each(someJsonData, function (index, res) {
{
 questionNumber++;
 new_question = "<div id=\"" + res.qId + "\">" +
                            "<h1>Question "+questionNumber+"</h1>" +
                            "<p><i>" + res.question + "</i></p>" +
                            "<div class=\"answer-grid\">" +
                            "<div id=\"a1\" class=\"answer\">" +
                            "<p>" + res.answer1 + "</p>" +
                            "<p>" + res.answer2 + "</p>" +
                            "<p>" + res.answer3 + "</p>" +
                            "</div>" +
                            "</div>";

}