jQuery 等到上一个 .append() 完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1539841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:40:54  来源:igfitidea点击:

Wait until previous .append() is complete

jqueryappend

提问by bluwater2001

How can we make appendwait until the previous appendis complete. I am appending huge amount of data so the present append should check if the previous append is complete. I am able to do this by giving all the append's independently with some time delay. But practically according to my code I may have 'n' number of appends so I want to do this dynamically.

我们如何才能append等到前一个append完成。我正在追加大量数据,因此当前追加应该检查上一个追加是否完整。我可以通过在一些时间延迟后独立地提供所有附加来做到这一点。但实际上根据我的代码,我可能有“n”个附加项,所以我想动态地执行此操作。

I tried using for or while loop but the script is getting corrupted and the browser is crashing because the next append is starting before the previous append is complete.

我尝试使用 for 或 while 循环,但脚本已损坏并且浏览器崩溃,因为下一个追加在上一个追加完成之前开始。



$('#printall1').click(function() {
$('#fourElementsonly').empty();
var cleartable = 0;
var maxlimit = 0;
var presentarraycount = 0;
$.post("/PortalUserReport/getjunkdata", null, function(response, status) {
    var report = eval(response);
    var totalRecordsCount = report.length; //6000
    var totalRecordsCountfortheLoop = totalRecordsCount;
    var arraycount = Math.ceil(totalRecordsCount / 1000);
    var reports = new Array(arraycount); // reports[6]
    for (var i = 0; i < arraycount; i++) {
        $('#fourElementsonly').append('<table border = "1" id = "Portal_User_elements' + i + '" style = " border-collapse:collapse; width:800px; margin:0px; padding:0px; border-color:black"> </table>');
    }
    reports[presentarraycount] = "";
    $.each(report, function(x) {
        if (cleartable == 0) {
            for (var i = 0; i < arraycount; i++) {
                $('#Portal_User_elements' + i).empty();
            }
            cleartable++;
        }
        if (recordnumber <= totalRecordsCountfortheLoop) {
            reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td style = \"width:50px; text-align:center \"> " + recordnumber + " </td>   <td style = \"width:350px;\"> Name :" + report[x].FirstName + "</td> <td style = \"width:200px;\"> UserName :" + report[x].UserName + " </td> <td style = \"width:200px; \"> Company : " + report[x].Company + " </td> </tr>";
            reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td > </td> <td> Registration Date : <label class = \"datepicker\"> " + report[x].ActiveDate + " </label> <td> User CN : " + report[x].UserCN + " </td> <td> Status: " + report[x].Status + " </td> </ td>  </tr>";
            reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td> </td> <td> User Privilege : " + report[x].Privileges + " </td> <td> </td> </tr>";
            maxlimit++;
            if (maxlimit == 1000) {
                presentarraycount++;
                reports[presentarraycount] = "";
                maxlimit = 0;
            }
        }
        recordnumber++;
    });
    for (var i = 0; i < arraycount; i++) {
       $(this).delay(1000, function() {
            $('#Portal_User_elements' + i).append(reports[i]);
       });
    }
});

});

采纳答案by bluwater2001

The below solution is working on all the browsers especially IE6. The response time in Firefox is 10 sec, but in IE6 it is 2 min 30 sec.

以下解决方案适用于所有浏览器,尤其是 IE6。Firefox 中的响应时间为 10 秒,但在 IE6 中为 2 分 30 秒。

$('#printall1').click(function() {
    $('#fourElementsonly').empty();
    var cleartable = 0;
    var maxlimit = 0;
    var presentarraycount = 0;

    $.post("/PortalUserReport/getjunkdata", null, function(response, status) {
        var report = eval(response);// we have 6000 records in the report now
        var totalRecordsCount = report.length; // count = 6000 
        var totalRecordsCountfortheLoop = totalRecordsCount;
        var arraycount = Math.ceil(totalRecordsCount / 1000);
        var reports = new Array(arraycount); // reports[6]
        for (var i = 0; i < arraycount; i++) {
            $('#fourElementsonly').append('<table border = "1" id = "Portal_User_elements' + i + '" style = " border-collapse:collapse; width:800px; margin:0px; padding:0px; border-color:black"> </table>');
        }
        reports[presentarraycount] = "";
        $.each(report, function(x) {
            if (cleartable == 0) {
                for (var i = 0; i < arraycount; i++) {
                    $('#Portal_User_elements' + i).empty(); 
                }
                cleartable++;
            }

            if (recordnumber <= totalRecordsCountfortheLoop) {
                reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td style = \"width:50px; text-align:center \"> " + recordnumber + " </td>   <td style = \"width:350px;\"> Name :" + report[x].FirstName + "</td> <td style = \"width:200px;\"> UserName :" + report[x].UserName + " </td> <td style = \"width:200px; \"> Company : " + report[x].Company + " </td> </tr>";
                reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td > </td> <td> Registration Date : <label class = \"datepicker\"> " + report[x].ActiveDate + " </label> <td> User CN : " + report[x].UserCN + " </td> <td> Status: " + report[x].Status + " </td> </ td>  </tr>";
                reports[presentarraycount] += "<tr style = \"height:20px;  border: 1px Solid Black\"> <td> </td> <td> User Privilege : " + report[x].Privileges + " </td> <td> </td> </tr>";
                maxlimit++;
                if (maxlimit == 1000) {
                    presentarraycount++;
                    reports[presentarraycount] = "";
                    maxlimit = 0;
                }
            }
            recordnumber++;
        });

        for (var i = 0; i < arraycount; i++) {
            $('#Portal_User_elements' + i).append(reports[i]);
        }
    });
});

回答by idrumgood

Unfortunately, the jQuery append()function does not include a callback. There is no way to really check for completion of it, as it supposedly happens immediately.

不幸的是,jQueryappend()函数不包括回调。没有办法真正检查它是否完成,因为它应该立即发生。

See Herefor some info on how to use append efficiently. What it pretty much gets at is you can try to get all of your text into one variable and simply use append once.

有关如何有效使用 append 的一些信息,请参见此处。它的主要内容是您可以尝试将所有文​​本放入一个变量中,然后简单地使用 append 一次。

[update] Since you have all your data in a JSON object from the get go, just do your looping through and put it all in a variable, then just append that once you're finished. [/update]

[更新] 由于您从一开始就将所有数据放在一个 JSON 对象中,只需进行循环并将其全部放入一个变量中,然后在完成后追加它。[/更新]

回答by Zakk Diaz

Based on the answer from Tim Gard, I found this solution to be very elegant...

根据 Tim Gard 的回答,我发现这个解决方案非常优雅......

$(".selector").append(content).append(function() { /*code goes here to run*/ });

回答by Alex Bagnolini

I can give you some hints on how to improve your code.

我可以给你一些关于如何改进你的代码的提示。

    for (var i = 0; i < arraycount; i++) {
        $('#fourElementsonly').append('<table border = "1" id = "Portal_User_elements' + i + '" style = " border-collapse:collapse; width:800px; margin:0px; padding:0px; border-color:black"> </table>');
    }

Can become:

可以变成:

   var html = '';  
   for (var i = 0; i < arraycount; i++) {
       html += '<table border = "1" id = "Portal_User_elements' + i + '" class="portalUserElements"> </table>';
    }
    $('#fourElementsonly').append(html);

You will accomplish:

你将完成:

  • 999 less jquery selections to '#fourElementsonly'
  • less code to be injected if you put in the class "portalUserElements" the styles:
    border-collapse:collapse; width:800px; margin:0px; padding:0px; border-color:black
  • 对“#fourElementsonly”的 999 个 jquery 选择
  • 如果您将样式放入“portalUserElements”类,则注入的代码更少:
    border-collapse:collapse; 宽度:800px;边距:0px;填充:0px; 边框颜色:黑色

This means you can also:

这意味着您还可以:

   for (var i = 0; i < arraycount; i++) {
        $('#Portal_User_elements' + i).empty(); 
    }

becomes (no for loop!):

变成(没有 for 循环!):

   $('.portalUserElements').empty();

And:

和:

for (var i = 0; i < arraycount; i++) {
    $('#Portal_User_elements' + i).append(reports[i]);
}

Maybecome:

可能变成:

$('.portalUserElements').each(
     function(i) {
         $(this).append(reports[i]);
     }
);

Edit: these changes are suggested to improve your algorithm performance, while maintaining the full feature it provides.
You may want to compact everything inside a single string variable (including tables) and append it at the end.
See the articles that Russ Cam suggested you in one of his answers.

编辑:建议进行这些更改以提高您的算法性能,同时保持它提供的完整功能。
您可能希望压缩单个字符串变量(包括表)中的所有内容并将其附加到末尾。
请参阅 Russ Cam 在他的一个答案中向您推荐的文章。

回答by Tim Gard

A clunky way...

笨拙的方法...

One function (the existing function) handles all of the appends. The code that had followed the appends is wrapped in a new function "kickOffTheRestOfTheProcess".

一个函数(现有函数)处理所有的追加。附加后的代码包含在一个新函数“kickOffTheRestOfTheProcess”中。

After all of your initial appends, you add have one final append. It won't get executed until all the others.

在所有初始追加之后,您添加了一个最终追加。在所有其他人之前,它不会被执行。

$('body')).append("<script>kickOffTheRestOfTheProcess();</script>");

It's worked for me.

它对我有用。

回答by Karl Zillner

Very simple :)

很简单 :)

Using whenfunction.

使用when函数。

$('<div id="appendedItem">Here</div>').appendTo("body");
$.when( $("#appendedItem").length > 0).then(function(){
    console.log( $("#appendedItem").length );
});

回答by Rowan

Are you appending to different elements or to a single element? If you're appending to a single element, it may be easier to concatenate all of your data and append as one chunk.

您是附加到不同的元素还是附加到单个元素?如果您要附加到单个元素,则连接所有数据并附加为一个块可能会更容易。

Also, where is the data from? If the data is static (non ajax) then you should be able to call

还有,数据是哪里来的?如果数据是静态的(非 ajax),那么你应该可以调用

$('selector').append(data1).append(data2).append(data3);

回答by rism

Perhaps another way might have been to simply check whether the length of the innerHTML of the container you're appending to equals the length of the last chunk of content, within your polling function.

也许另一种方法可能是在轮询函数中简单地检查您要附加到的容器的 innerHTML 的长度是否等于最后一块内容的长度。

If not dont append, if so append.

如果不是不追加,如果是追加。

回答by Helzgate

building on the guys answers above i did this in angular:

建立在上面的人的答案的基础上,我在 angular 中做到了这一点:

el.append('<span>random stuff</span>').append('{{randomFunction()}}');