This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                                
                                    (6个答案)
                                
                        
                2年前关闭。
            
        

我知道这是一个非常常见的问题,即使我已经解决了很多次此类问题,也已经回答了很多这样的问题,但是这次我被困在这一点上。我尝试应用许多解决方案,但对我没有任何帮助。

这是我的JS的样子:

jQuery(document).ready(function($){
    avHomePageThumbnails();
    var slideIndex = 0; showSlides();


    function avHomePageThumbnails(){
        let homePagePosts = JSON.parse(posts_data);
        homePagePosts.map( homePagePost => {
            let screenID = homePagePost.query_vars.meta_value;
            if(homePagePost.posts.length > 0){
                homePagePost.posts.map(( post, i ) => {
                    let postID = post.ID;
                    let postURl = post.guid;
                    $.post(ajax_url, {
                    action: "av_get_post_data_by_id",
                    id: postID
                    }, function(resp){
                        //console.log(resp, screenID);
                        resp = JSON.parse(resp);
                        let data = ''+
                        '<div class="mySlides fade">'+
                            '<a href="'+postURl+'">'+
                                '<img src="'+resp.image+'" style="width:100%">'+
                                '<div class="text">'+resp.title+'</div>'+
                            '</a>'+
                        '</div>';
                        $(".home-screen-thumb-container #"+screenID).append(data);

                    });
                } );
            }
        });
        //console.log(homePagePosts);
    }


function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    //var slides = $(".home-screen-thumb-container").find(".mySlides");
    console.log(slides);
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display="none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}

    slides[slideIndex-1].style.display = "block";
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}
});


在这里,我无法在mySlides中选择div showSlides()

最佳答案

在您调用showSlides()时,您的其他函数avHomePageThumbnails()尚未完成其(异步)ajax调用。

您的解决方案是从ajax-call(showSlides())的回调函数中调用$.post()(在添加div的那部分之后)。或者(更好),使avHomePageThumbnails()返回一个承诺,并在承诺完成后调用showSlides()

在这里快速介绍承诺:
https://developers.google.com/web/fundamentals/primers/promises

10-02 21:46