gpt4 book ai didi

javascript - .when .done 函数未运行

转载 作者:行者123 更新时间:2023-11-30 11:02:05 26 4
gpt4 key购买 nike

我有一个小脚本,它使用函数 getJSON 将 json 字符串保存到 var。之后我想用内容创建一些 div。

为此,我为猫(类别)创建了一个 each。在第二个中,当 repo 适合猫时,它也应该显示。但是脚本永远不会转到 .when 或 .each 函数。但是使用 console_log() 我看到了来自 getJSON 函数的正确响应。

var repo;
var cat;
$.getJSON("api.php?get_repos&release_id=" + $("#release").find(":selected").data('id'), function (
json) {
repo = json;
});
$.getJSON("api.php?get_cat", function (json) {
cat = json;
});
$.when(repo, cat).done(function(){
$.each(cat, function (i, j) {
$(".tab").append('<button class="tablinks" onclick="openCAT(event, \'' + j.cat_name + '\'">' + j.cat_name + '</button>');
$(".repos").append('<div id="' + j.cat_name + '" class="tabcontent"></div>');
$.each(repo, function (k, v) {
if (v.repo_cat == j.cat_id) {
$("#"+ j.cat_name).append('<div class="repo"></div><p><label><input name="3rdparties[]" type="checkbox" value="' +v.repo_id + '"> ' + v.repo_name +'</label>&nbsp;&nbsp;<a href="' + v.repo_homepage +'" target="_blank" class="link"><i class="icon ion-earth"> Homepage</i></a>&nbsp;&nbsp;<a href="' + v.repo_documentation +'" target="_blank" class="link"><i class="icon ion-university"> Documentation</i></a>');
$("#"+ j.cat_name).append('<div class="inside">' + v.repo_desc + '');
$("#"+ j.cat_name).append('<a href="#" onClick="brokenRepo(\'' + v.repo_id +'\');" class="link right"><i class="icon ion-flash-off"> Broken Repo</i></a></div></p></div><br />');
}
});
});
});

最佳答案

有两个问题:

  1. repo,cat 是 JSON 值,不是 promise 或 deferred 对象,所以 $.when 不会有任何效果

  2. repo,cat 仅在 $.getJSON 完成后设置,因此在 $.when

    时不可用>

您需要记录从 $.getJSON 返回的 jquery promise 以与 $.when 一起使用:

var repo;
var cat;
var repoPromise = $.getJSON("api.php?get_repos&release_id=" + $("#release").find(":selected").data('id'), function(json) {
repo = json;
});
var catPromise = $.getJSON("api.php?get_cat", function(json) {
cat = json;
});
$.when(repoPromise, catPromise).done(function() {
$.each(cat, function(i, j) {
...
$.each(repo, function(k, v) {
if (v.repo_cat == j.cat_id) {
...
}
});
});
});

关于javascript - .when .done 函数未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57308136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com