微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

也许没有什么区别,但是要比其他方式好(或者也许是比两者都更神秘的“第三”方式)!)

第一:

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));
    });

});

第二:

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));
    });

});

解决方法

一个有趣的事实是,ajaxStart等实际上只是jQuery事件。例如:
$("#lbl_ajaxInProgress").ajaxStart(function() {
  // update labels
  $(this).text('Yes');
});

相当于:

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

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

$("#lbl_ajaxInProgress").unbind("ajaxStart ajaxStop");

你也可以做:

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

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

接着:

$("#lbl_ajaxInProgress").unbind(".label");

很酷啊

原文地址:https://www.jb51.cc/jquery/181787.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐