我有几个(可能超过2个)类似DIV的html:
<div class="article">
<img id="img" src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/51/IBM_logo.svg/400px-IBM_logo.svg.png" />
<div class="text2ls">IBM</div>
</div>
<hr/>
<div class="article">
<img id="img" src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/96/Microsoft_logo_%282012%29.svg/440px-Microsoft_logo_%282012%29.svg.png" />
<div class="text2ls">Microsoft</div>
</div>
并希望将它们作为JSON字符串添加到localStorage中。这是我的jQuery:
$('.article').each(function () {
var imageUrl = $(this).find('img[id=img]').attr('src');
convertImgToBase64(imageUrl, function (base64Img) {
localStorage.setItem('elephant', base64Img);
var picture = localStorage.getItem('elephant');
lsengine(picture);
});
});
function lsengine(pic) {
var copy = $('.text2ls').html();
var article = {
"text": copy,
"image": pic
};
localStorage.setItem('articles', JSON.stringify(article));
localStorage.removeItem('elephant');
}
但由于某些原因,它只增加了一个DIV的内容。你能帮我解决一下我的错误吗?
请与我的jsfiddle一起玩:http://jsfiddle.net/5eq3koco/2/
答案 0 :(得分:1)
您在localStorage.setItem('articles', JSON.stringify(article));
循环的每次迭代中调用$.each
。你可以做的是拥有一个全局数组来存储每个文章对象,并在循环结束后对其进行字符串化。类似的东西:
var articles = [];
$('.article').each(function () {
var imageUrl = $(this).find('img[id=img]').attr('src');
convertImgToBase64(imageUrl, function (base64Img) {
localStorage.setItem('elephant', base64Img);
var picture = localStorage.getItem('elephant');
lsengine(picture);
});
});
function lsengine(pic) {
var copy = $('.text2ls').html();
articles.push({
"text": copy,
"image": pic
});
}
localStorage.setItem('articles', JSON.stringify(articles));
localStorage.removeItem('elephant');
编辑你的小提琴演示的第二个问题是stringify函数会立即发生,因为你的img.onload会触发你对localStorage的写入异步发生。看看这个:https://jsfiddle.net/limdauto/5eq3koco/8/