gpt4 book ai didi

javascript - 在javascript中使用本地存储保存图像

转载 作者:行者123 更新时间:2023-12-03 01:42:28 26 4
gpt4 key购买 nike

检查我的 JS fiddle :https://jsfiddle.net/oxfre6kj/1/

我有一个按钮可以根据需要创建任意数量的图像,但是当我刷新页面时,这些图像消失了,我希望在单击“保存”按钮后它们仍然存在。

这是我尝试过的,它适用于变量,但不适用于“img”

<button onclick="createImage()">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<div id="image"></div>

<script>
function createImage() {
var img = document.createElement('img');
img.src = 'http://via.placeholder.com/350x150';
document.getElementById('image').appendChild(img);
}


var image = localStorage.getItem('image');
alert(image);

function saveImage() {
localStorage.setItem("images", image);
}
</script>

最佳答案

这就是您希望页面工作的方式吗?

HTML:

<button id="create_image">Create Image</button>
<button onclick="saveImages()">Save Images</button>

<label for="image_url">Image url :</label>
<input type="text" id="image_url" value="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" placeholder="img url">

<div id="images"></div>

JavaScript:

document.getElementById("create_image").addEventListener("click", function() {
const url = document.getElementById("image_url").value;
createImage(url);
});

var images = localStorage.getItem('image');
loadImagesFromLocal();

function createImage(src) {
var img = document.createElement('img');
img.src = src;
img.onload = function() {
document.getElementById('images').appendChild(img);
}
}

function saveImages(img) {
const images = document.querySelectorAll(`div#images img`);
var savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
savedImagesSrc = Array.from(savedImagesSrc);

for (var i = savedImagesSrc.length; i < images.length; i++) {
savedImagesSrc.push(images[i].src);
}

localStorage.setItem("images", JSON.stringify(savedImagesSrc));
}

function loadImagesFromLocal() {
const savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];

for (var i = 0; i < savedImagesSrc.length; i++) {
createImage(savedImagesSrc[i]);
}

}

关于javascript - 在javascript中使用本地存储保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50775380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com