簡體   English   中英

我的$ .when塊中的代碼未使用jQuery觸發

[英]My code inside `$.when` block is not firing with jQuery

我試圖在jQuery中使用$.when(some function).then(some function)強制回調函數等待,直到$.when()的代碼先完成。

這是我的功能。

function activateFirstTab(callback) {

    console.log('started activateFirstTab');
    console.log('Total groups found: '+ $('.functionParameterGroup').length);

    $.when(function () {

        $('.functionParameterGroup').each(function () {
            //Activate the first tab "which is the default"

            var first = $(this).find('ul > li:first');

            first.addClass('active');

            var contentId = first.data('contentid');

            $(contentId).addClass('in active');

            console.log('finished when logic in activateFirstTab');

        });

    }).then(function () {

        // Make sure the callback is a function​
        if (typeof callback === "function") {
            // Call it, since we have confirmed it is callable​
            callback();
        }

    });


    console.log('finished activateFirstTab');

}

在控制台中,我收到以下消息

started activateFirstTab
Total groups found: 2
finished activateFirstTab

但是我從來沒有從$.when()內部的塊中獲得消息

我期望輸出是這個

started activateFirstTab
Total groups found: 2
finished when logic in activateFirstTab
finished when logic in activateFirstTab
finished activateFirstTab

為什么$.when()的代碼未執行?

我該如何執行它? 我犯什么錯誤?

您不要在$.when()內調用該函數,還要注意傳遞給$.when()的匿名函數不會返回promise。 盡管任何類型的參數都可以傳遞給$.when()

 function fn(callback) { $.when(function dfd(callback) { $.each([1, 2, 3], function(i, value) { console.log(value) }); return "dfd complete" }() /* invoke `dfd` function */ ) .then(function(data) { // Make sure the callback is a function​ if (typeof callback === "function") { // Call it, since we have confirmed it is callable​ callback(data); } }) } fn(function(args) { alert(args) }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM