来自循环的JQuery内容最后添加

时间:2013-08-22 09:36:22

标签: jquery loops for-loop jquery-append

基本上我需要附加标题,内容和页脚消息。

内容来自一个循环,由于某种原因它会追加到最后。

    function sendMail(){

    $("#textareaContainer").append('<textarea id="someTextarea" rows=12 class="span7">Some header text that is needed</textarea>');

    for (var i=0;i<idToUse.length;i++){
        $.post("actions.php", "do=contentFromPhp"+"&id="+idToUse[i],0,"json").done(function(result) {
        for (var i=0;i<result.length;i++){
        $("#someTextarea").append("\r"+result[i].theContent);
        }
    idToUse = [];
    });

    }
    $("#someTextarea").append("\rSome footer text that is needed!");

}

目前的输出是:

Some header text that is needed
Some footer text that is needed!
Content From loop 1
Content From loop 2

我需要它:

Some header text that is needed
Content From loop 1
Content From loop 2
Some footer text that is needed!

2 个答案:

答案 0 :(得分:0)

这是因为你使用ajax来填充数据,注意:即使这可能也不会给出确切的结果,因为ajax请求可能以不同的顺序返回

function sendMail(){

    $("#textareaContainer").append('<textarea id="someTextarea" rows=12 class="span7">Some header text that is needed</textarea>');

    var xhrs = [], xhr;
    for (var i=0;i<idToUse.length;i++){
        xhr = $.post("actions.php", "do=contentFromPhp"+"&id="+idToUse[i],0,"json").done(function(result) {
            for (var i=0;i<result.length;i++){
                $("#someTextarea").append("\r"+result[i].theContent);
            }
            idToUse = [];
        });
        xhrs.push(xhr)
    }

    $.when.apply($, xhrs).then(function(){
        $("#someTextarea").append("\rSome footer text that is needed!");
    })

}

答案 1 :(得分:0)

您需要在AJAX回调函数中附加页脚:

for (var i=0;i<idToUse.length;i++){
    $.post("actions.php", {
        do: "contentFromPhp",
        id: idToUse[i]
    }, 0, "json").done(function(result) {
        for (var i=0;i<result.length;i++){
            $("#someTextarea").append("\r"+result[i].theContent);
        }
        $("#someTextarea").append("\rSome footer text that is needed!");
        idToUse = [];
    });
}

我还将数据从字符串更改为对象,以便jQuery对其进行URL编码。