在具有全局变量的循环内调用图像加载 [英] Calling image onload inside a loop with global variable
问题描述
变量menuitems
是一个键值对.键包含名称,值包含图像URL.想法是将以下URL存储在本地存储中.
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.
本地存储变量为key_icon
(键是图像的名称)
Local Storage variable is key_icon
(key is the name of the image)
下面是代码.假设有4个键,分别为account
,sms
,group
和history
.
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);
}
}
});
由于onload
是asynchronous
,因此变量menu_icon_session_name
被覆盖,所有图像都存储在最后一个变量history_icon
中.
Since the onload
is asynchronous
the variable menu_icon_session_name
is overwritten and all images are stored on the last variable history_icon
.
我要做的就是将所有4张图像加载到单独的本地存储中,并在以后使用...
All I am trying to do is load all the 4 images to separate localstorage and use it later...
推荐答案
...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...
这篇关于在具有全局变量的循环内调用图像加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!