douweng1904 2018-04-20 13:10
浏览 55
已采纳

Jquery每个函数都没有按顺序排列

Why when using each loop, the returned values are not in the same order?

I have a code in php

 $selectedYear = 2018;
 $months = array (
         0 => 'January',
         1 => 'February',
         ...
         11 => 'December'
        );

Now, foreach $months i want to create new row (<tr>) with different value etc. I'm using AJAX for it like:

var selectedYear = <?= json_encode( $selectedYear ) ?>;
var month= <?= json_encode( $months); ?>;

$(month).each(function(k)
        {
            $.ajax({
                type      : 'POST',
                url       : 'scripts/ajax-monthTr.php',
                data      : {month: k, selectedYear: selectedYear},
                beforeSend: function()
                {
                    $('.preloader').css('display', 'block');
                },
                success   : function(data)
                {
                    $('#newTr').append(data);
                    $('.preloader').css('display', 'none');
                }
            }); // end ajax
        });

And i've got result not in order like:

<table>
   <tr id="0">January</tr>
   <tr id="3">April</tr>
   <tr id="2">March</tr>
   <tr id="5">July</tr>
   <tr id="1">"February"</tr>
   ...
</table>

Any solution for it? Have i missed something?

I tried

$(month).each(function(k)

or

for(var i = 0; i < month.lenght; i++)
  • 写回答

3条回答 默认 最新

  • dptn69182 2018-04-20 13:15
    关注

    That's because result of each ajax call is returning data at different interval. You can:

    1) Either append the data before calling ajax function.

    2) or, sort the tr elements based on id attribute after appending new row in every ajax function

     var items = $('#newTr tr');
     items.sort(function(a, b){
       return $(a).attr('id') - $(b).attr('id');
     });
    
     items.appendTo('#newTr');
    

    Working Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应