13

我有问题..

for(a=1;a<10;a++){
    $(".div").append("<div id="+a+"></div>")
        $.ajax({
              url: "file.php",
              data: "a="+a,
              type: "POST",
              async: false,
              success: function(data) {
                $("#"+a).html(data);
              }
        });

}
 $("div").click(function(){
        alert("it works");
 });

问题是:我没有把async: false来自file.php的数据放在最后一个 div 中,所以 id 为 9 但现在有async: false- 所以数据在每个 div 中,所以这很好

但如果我想在通过 ajax 加载时单击它不起作用(仅在完成所有 ajax-es 后)

如何解决这个问题?(也许错误的是我在使用 ajax。我可以使用 getJSON 等。)

谢谢你的帮助

4

2 回答 2

27

如果您希望用户能够在 ajax 调用运行时使用该界面,您应该将您asynctrue. James Allardice 还指出,在这种情况下id,当返回 ajax 调用时,您需要使用 javascript 闭包来保留原始值。有关 javascript 闭包的更多信息,请查看how-do-javascript-closures-work,这是在 stackoverflow 上找到的一个非常好的问题。

for(id = 1; id < 10; id++){
    $(".div").append("<div id='" + id + "'></div>");

    (function(id) {
        $.ajax({
            url: "file.php",
            data: "a=" + id,
            type: "POST",
            async: true,
            success: function(data) {
                $("#"+ id).html(data);
            }
        });
     }(id));
}
于 2012-06-28T14:38:47.150 回答
1

一个很好的解决方案是使用递归函数。

function appendDivs(limit, count) {
    count = count || 1;
    if (count <= limit) {
        $(".div").append("<div id=" + count + "></div>");
        $.ajax({
            url: "file.php",
            data: "a=" + count,
            type: "POST",
            async: true,
            success: function(data) {
                $("#" + count).html(data);
                appendDivs(limit, count + 1);
            },
            error: function(e) {
                alert('Error - ' + e.statusText);
                appendDivs(limit, count + 1);
            }
        });
    } else {
        return false;
    }
}
appendDivs(10);
于 2013-07-16T09:42:59.093 回答