我怎么能让$ .each等到.trigger('click')事件加载所有东西?

Chr*_*s M 8 jquery

在$ .getJSON成功函数中,我首先触发另一个元素的click事件:

$('#' + data[0].ID).trigger('click');
Run Code Online (Sandbox Code Playgroud)

触发的click事件有自己的$ .getJSON方法将一堆数据加载到div中.触发事件后的下一行:

$.each(data[0].ListEntries, function (key, val) {
        //this relies on the triggered click event 
        //having completely loaded all data!
}
Run Code Online (Sandbox Code Playgroud)

起初$ .each似乎没有做任何事情,但我在触发事件后立即添加了警报.响应警报后,$ .each中的代码显示了它应该是什么.

我猜测$ .each在点击事件完成加载数据之前正在运行.

setTimeout暂停足够长的时间以使click事件加载数据,但我宁愿不设置任意时间:

setTimeout(function() { 
    $.each(data[0].ListEntries, function (key, val) {
        //this relies on the triggered click event 
        //having completely loaded all data!
    }
}, 1000);
Run Code Online (Sandbox Code Playgroud)

我也试过$ .when和$ .then无济于事(尽管在$ .each里面添加警报,然后在$.然后为$ .each工作创建延迟):

$.when($('#' + data[0].ID).trigger('click')).then(function () {
    $.each(data[0].ListEntries, function (key, val) {
        //this relies on the triggered click event 
        //having completely loaded all data!
    })
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

您可以为此使用自定义事件.您可以将您$.each置于事件的监听器中,然后您的$.getJSON成功处理程序可以触发该事件:

$('#x').click(function() {
    var _this = this;
    $.getJSON(url, data, function(data) {
        // do things to data...
        _this.trigger('data-loaded');
    });
});
$('#x').on('data-loaded', function() {
    $.each(...)
});
$('#x').click();
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/ambiguous/FeYTB/


Bee*_*oot 6

整理得更清晰

.trigger()返回一个jQuery对象,因此您被拒绝执行该操作$.when() ... $.then().

另一方面,.triggerHandler()将返回您选择的对象,从而可以执行延迟技巧.

您的代码分为三个功能,简化如下.调用路径是1,2,3,最重要的返回路径是3,2,1.

(1)最高级别(JSON成功)功能将包括以下几行:

function() {
    ...
    $.when($('#' + data[0].ID).triggerHandler('click')).done(function() {
        $.each(data[0].ListEntries, function (key, val) {
            ...
        });
    });
    ...
};
Run Code Online (Sandbox Code Playgroud)

(2)由(1)触发的点击处理程序如下:

$("img.Button").on("click", function () {
    return GetModels(this.id);//here `return` passes on the jqXHR object, up the return path.
});
Run Code Online (Sandbox Code Playgroud)

(3)包含JSON的最低级函数(1)所依赖的函数将具有以下一般形式:

function GetModels(id) {
    ...
    var jqXHR = getJSON(function(){...});
    ...
    return jqXHR;//it is vital to retutn the jqXHR object arising from the json call.
}
Run Code Online (Sandbox Code Playgroud)

备注:

  • 返回路径作为.when()(1)中方法的"promise"参数传递由.getJSON()(3)中的调用产生的jqXHR对象..done()因此,在触发作为其参数提供的函数之前,(1)中的链接被迫等待jqXHR被解析(即完成).
  • click处理程序不会假设它是如何被调用的.它只返回jqXHR对象.因此,在使用时.triggerHandler(),单击处理程序可以附加其他行为,而不会影响正常的单击操作.
  • GetModels()从(1)直接调用,切断中间人(2)会更简单,如果GetModels()行为是唯一需要的话,这很好.但是,如果(1)需要响应未来对触发的点击处理程序(2)的任何更改,则需要采用上述方法.