jQuery将动态创建的列表放在<ul>标记</ul>中

时间:2011-05-19 09:27:53

标签: jquery list append

.append()似乎无法解决问题,它将<ul></ul>放在顶部。 我应该怎么做?

fullQuestion只针对每个问题生成一个<li>

function writeQuestions() {

$('#container').append("<ul>\n");

len = questions.qestion.length;
for (var i = 0; i < len; i++) {

        var answerRdy = [];
        var qestionRdy = questions.qestion[i];
        answerRdy[0] = questions.answer[i][0];
        answerRdy[1] = questions.answer[i][1];
        answerRdy[2] = questions.answer[i][2];
        answerRdy[3] = questions.answer[i][3];
        var divID = "question-" + i;
        var formID = "form-" + i;
        var CurrentForm = i;

            var writeAnswer = [];
            writeAnswer[writeAnswer.length] = ("\n<br />`<li id='{0}'>`\n<form id='{1}' name='{2}'>\n").format(divID, formID, CurrentForm);
            writeAnswer[writeAnswer.length] = ("<b>" + qestionRdy + "</b><br />\n");
        for (var n=0; n<=3; n++) {
            writeAnswer[writeAnswer.length] = ("<input type='radio' name='answerN' value='{0}' /> {1} <br />\n").format(n, answerRdy[n]);
                }
            writeAnswer[writeAnswer.length] = ("<input type='submit' value='Submit your answer'>\n</form>\n</li><!--{0}-->").format(divID);


        var joinQuestion = writeAnswer.join();
    //  var joinQuestion = "<ul>\n" + joinQuestion + "\n</ul>"
            exp = /,/gi;
        var fullQuestion = joinQuestion.replace(exp, "");

    $('#container').append(fullQuestion);
}

for (var i=0; i < len; i++) {
    var formID = document.forms["form-" + i];
    $(formID).bind("submit", validate);
}

$('#container').append("\n</ul>");

}

2 个答案:

答案 0 :(得分:3)

您没有正确使用追加。

首先创建UL

var $ul = $('<ul>');
$('#container').append($ul);
//all other code
$ul.append(fullQuestion);

并删除此行$('#container').append("\n</ul>");

答案 1 :(得分:0)

试试这个应该在ul

中插入fullQuestion字符串

$('#container ul')。html(fullQuestion);