匿名函数给出“;undefined不是函数“;在回调中

Anonymous function gives "undefined is not a function" in callback

本文关键字:函数 回调 undefined      更新时间:2023-09-26

运行以下代码时,在"back.ajax({"一行,我得到了一个"UncaughtTypeError:undefined is not a function"。我已经阅读了jQuery文档,这似乎已经完成了任务。我还验证了jQuery是否包括在内,浏览器是否识别"$"。CURRYEAR已经定义,并且所有引用的元素都存在。如果我使用相同的代码作为对.load()的回调然后它执行得很好,但我需要同步执行,因为while循环在异步调用时只执行一次。

代码:

function loadWL() {
  var back = $("#back-results");
  var numYears;
  var year;
  var count = 0;
  var wArr = [];
  var lArr = [];
  var dArr = [];
do {
    year = CURRYEAR - count;
    var standingsURL = STANDINGS.replace(" ", localStorage["leagueID"]);
    standingsURL = standingsURL.replace(",", year);
    var yqlStand = 'https://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + standingsURL + '"') + " #maincontainertblcell";
    //Load into the hidden pane
    var id;
    var self = this;
    back.html("");
    back.ajax({
        url: yqlStand,
        async: false
    }).done(function() {
        //Parse the number of years the league has been active
        if (count == 0) {
            numYears = $("select > option").length;
        }
        //Narrow to only the elements we need
        $(self).html($("#back-results tr .tableBody"));
        //Now traverse the back pane and store info
        $("#back-results > .tableBody a").closest("tr").each(function(index) {  
            id = urlToID($(this).find("a").attr('href'));                                       
            if (typeof wArr[id] == 'undefined') {
                wArr[id] = 0;
                lArr[id] = 0;
                dArr[id] = 0;
            }
            wArr[id] = wArr[id] + parseInt($(':nth-child(2)', this).text().trim(),10);                                  
            lArr[id] = lArr[id] + parseInt($(':nth-child(3)', this).text().trim(), 10);                                 
            dArr[id] = dArr[id] + parseInt($(':nth-child(4)', this).text().trim(), 10);                                 
            if (count == numYears-1) {
                arrayToLocal(wArr, "wins");
                arrayToLocal(lArr, "losses");
                arrayToLocal(dArr, "draws");
            }
        });
        count++;
        return;
    });
} while (count < numYears);

}

back.ajax({...})应为$.ajax({...})

ajax调用是全局的,它不绑定到任何特定的对象,所以你不在jQuery对象上调用它,而是在jQuery命名空间对象上调用。


此外,您确实应该修复ajax以使用async: true,这样它就不会在ajax调用期间锁定浏览器。这需要将while循环更改为不同类型的结构,以便对异步ajax调用进行排序。