使用全局变量在循环内调用图像onload

时间:2016-02-14 01:52:17

标签: javascript local-storage onload

变量data.txt是键值对。键包含名称,值包含图像URL。我们的想法是将以下URL存储在localstorage中。

本地存储变量为menuitems(键是图像的名称)

以下是代码。假设有4个密钥为key_iconaccountsmsgroup

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); } } }); onload,变量asynchronous会被覆盖,所有图片都会存储在最后一个变量menu_icon_session_name上。

我要做的就是将所有4张图片加载到单独的localstorage中,稍后再使用...

1 个答案:

答案 0 :(得分:2)

...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...