您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用jQuery延迟?

如何使用jQuery延迟?

我能想到的最佳用例是缓存AJAX响应。这是RebeccaMurphey关于该主题的介绍性帖子

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

基本上,如果该值在从缓存立即返回之前已经被请求一次。否则,AJAX请求将获取数据并将其添加到缓存中。的$.when/ .then不关心任何的这一点; 您需要关心的就是使用响应,.then()在两种情况下都将响应传递给处理程序。jQuery.when()手柄的非无极/延迟作为一个已完成,立即执行任何.done().then()上链。

对于任务可能会异步执行或可能不会异步执行以及您希望从代码中抽象出该条件的情况,Deferreds非常适合。

使用$.when助手的另一个真实示例:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});
JS 2022/1/1 18:13:36 有649人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶