Calling image onload inside a loop with global variable

£可爱£侵袭症+ 提交于 2019-12-13 18:45:53

问题


The variable menuitems is a key value pair. The key contains the name and the value contains the Image url. The idea is to store the below URL in the localstorage.

Local Storage variable is key_icon (key is the name of the image)

Below is the code. Assume there are 4 keys as account, sms, group and history.

$.each(menuitems, function(key, value) {
    menu_icon_session_name = key+'_icon';
    var dataImage = localStorage.getItem(menu_icon_session_name);

    //The Div container to load the image
    div  = "<div class='ui-block-a'><div class='ui-bar' id='div_"+key+"' style='padding:5px'>" +
    "<img crossorigin='anonymous' width=150 height=150 id='btn_"+key+"' style='height: 100%; width:100%'>"
    "</div></div>";

    //Append the div container with empty image
    jQuery('#pg_home_content').append(div);

    //Based on the local storage load the image
    if(dataImage){
        console.log('loaded from session');
        bannerImg = document.getElementById('btn_'+key);
        bannerImg.src = dataImage;
        jQuery('#div_'+key).html(bannerImg);
    }else{
        console.log('loaded from url');
        bannerImage = document.getElementById('btn_'+key);
        bannerImage.setAttribute('crossOrigin', 'anonymous');

        bannerImage.src = value.menu_icon;
        bannerImage.onload = function () {
            imgData = getBase64Image(bannerImage);
            localStorage.setItem(menu_icon_session_name, imgData);
            console.log('stored '+menu_icon_session_name);
        }
    }
});

Since the onload is asynchronous the variable menu_icon_session_name is overwritten and all images are stored on the last variable history_icon.

All I am trying to do is load all the 4 images to separate localstorage and use it later...


回答1:


...stuff...

    bannerImage.src = value.menu_icon;
    bannerImage.attr('data-my-session-name', menu_icon_session_name);
    bannerImage.onload = function () {
        imgData = getBase64Image(this);
        localStorage.setItem($(this).attr('data-my-session-name'), imgData);            

...stuff...


来源:https://stackoverflow.com/questions/35387534/calling-image-onload-inside-a-loop-with-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!