douxihui8270 2015-03-31 07:30
浏览 54
已采纳

检查jquery(或ajax)函数是否完成

I am currently running this code:

$("document").ready(function() {
    $(".tableCourses td:first").trigger('click');
    setTimeout(function() {
        $(".tableTutors tr:eq(1) td:eq(0)").trigger('click');
        setTimeout(function() {
            $(".tableForms tr:eq(1) td:eq(0)").trigger('click');
            setTimeout(function() {
                $(".tableDivision tr:eq(2) td:eq(3)").trigger('click');
            }, 800);
        }, 700);
    }, 600);
});

What this basically does is activate my onclick events for every first cell of every table I have.

Don't judge.. It's what I need. The setTimeout is kind of ugly, and it only works half of the time.

The problem is that every table has to be loaded with ajax, which can take some time. When I use this code:

$("document").ready(function() {
    $.when($(".tableCourses td:first").trigger('click')).then(function() {
        $.when($(".tableTutors tr:eq(1) td:eq(0)").trigger('click')).then(function() {
            $.when($(".tableForms tr:eq(1) td:eq(0)").trigger('click')).then(function() {
                $(".tableDivision tr:eq(2) td:eq(3)").trigger('click');
            });
        });
    });
});

the page only executes the first click handler, which is loading the next table. Am I using $.when and $.then wrong? Is my syntax wrong?

I normally never touch jquery or ajax, so I'm kind of in the dark.

Another note: the first click has to load two tables from two seperate php pages, so that one takes longer.

EDIT: I just realised that the $.when and $.then just work for the click activation, not the entire ajax loads. Any way to detect when those are done?

EDIT 2: This is the onclick event, it is almost the same for every click:

<script>
    function courseToTutor(id) {
        var clickedCourse = document.getElementById("course" + id).value;
        $.post('loadTutors', {postname: clickedCourse}, function() {
            $('#loadTutors').load('loadTutors.php');
            $('#loadForms').load('loadForms.php');
        });
        ;
        window.scrollTo(0, 0);
    }
</script>

It is complicated.. lol. I need to somehow check when these functions are done, before I start my next onclick event on page load?

  • 写回答

3条回答 默认 最新

  • doumen5895 2015-03-31 07:35
    关注

    jQuery ajax has callbacks for done, error and always.

    Check out the docs

    These functions are activated when call is ended successfully, with error, or eitherway (respectively).

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵