jQuery我应该使用多个ajaxStart/ajaxStop处理

dav*_*eps 16 jquery

也许没有区别,但要么比其他方式更好(或者可能是比两者更好的神秘'第三'方式!)......


第一:

var startTime;

$(document).ready(function() {

    $("#lbl_ajaxInProgress").ajaxStart(function() {
        // store the current date/time...
        startTime = new Date();
        // update labels
        $(this).text('Yes');
        $("#lbl_ajaxCallTime").text("-");
    });

    $("#lbl_ajaxInProgress").ajaxStop(function() {
        // update labels
        $(this).text('No');
        $("#lbl_ajaxCallTime").text(myFunctionThatCalculatesTime(startTime));
    });

});
Run Code Online (Sandbox Code Playgroud)

第二:

var startTime;

$(document).ready(function() {

    $("#lbl_ajaxInProgress").ajaxStart(function() {
        // update labels
        $(this).text('Yes');
    });

    $("#lbl_ajaxInProgress").ajaxStop(function() {
        // update labels
        $(this).text('No');
    });

    $("#lbl_ajaxCallTime").ajaxStart(function() {
        // store the current date/time...
        startTime = new Date();
        // update labels
        $(this).text("-");
    });

    $("#lbl_ajaxCallTime").ajaxStop(function() {
        // update labels
        $(this).text(myFunctionThatCalculatesTime(startTime));
    });

});
Run Code Online (Sandbox Code Playgroud)

Yeh*_*atz 43

一个有趣的事实是ajaxStart等实际上只是jQuery事件.例如:

$("#lbl_ajaxInProgress").ajaxStart(function() {
  // update labels
  $(this).text('Yes');
});
Run Code Online (Sandbox Code Playgroud)

相当于:

$("#lbl_ajaxInProgress").bind("ajaxStart", function() {
  // update labels
  $(this).text('Yes');
});
Run Code Online (Sandbox Code Playgroud)

这意味着您还可以将命名空间附加到ajaxStart/ajaxStop等.这也意味着您可以执行以下操作:

$("#lbl_ajaxInProgress").unbind("ajaxStart ajaxStop");
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

$("#lbl_ajaxInProgress").bind("ajaxStart.label", function() {
  // update labels
  $(this).text('Yes');
});

$("#lbl_ajaxInProgress").bind("ajaxStop.label", function() {
  // update labels
  $(this).text('No');
});
Run Code Online (Sandbox Code Playgroud)

然后:

$("#lbl_ajaxInProgress").unbind(".label");
Run Code Online (Sandbox Code Playgroud)

很酷,对吧?

  • 从jQuery 1.8开始,.ajaxStart()方法仅应附加到文档。 (2认同)