我正在寻找一种通过将所选图像存储在数组中来存储所选图像的方法。一旦保存了所选图像的索引,并单击了按钮(获取项(ID为“ done”),我就需要对数组中所选图像的URL进行字符串化处理,以便将其存储在localstorage中。我需要从本地存储中提取数据,然后将其转换回一个对象,在页面上写入所选图像,然后从页面上的本地存储导入所选图像。数组。
此外,我需要使用复选框来选择或取消选择该项目,但此刻只有在单击图像时它才起作用。
谢谢!请只使用javascript
<html>
<head>
<style>
img.selected {
opacity: 0.5;
}
</style>
</head>
<body onload="vegetable()">
<button id="done" onclick="new()">get item </button>
<div id="idmain"></div>
<script>
function new() {}
var hey = [
{ item: "knife", fruit: "banana.png" },
{ item: "fork", fruit: "apple.png" },
{ item: "sword", fruit: "kiwi.jpg" },
{ item: "spoon", fruit: "mango.jpg" }
];
function vegetable() {
for (var i = 0; i < hey.length; i++) {
var Img = document.createElement("img");
Img.setAttribute("src", hey[i].fruit);
Img.setAttribute("class", "posterImage");
var Div = document.createElement("div");
Div.setAttribute("class", "posterDiv");
Img.addEventListener("click", function() {
if (this.parentNode.getElementsByTagName("input")[0].checked) {
this.className = "posterImage unselected";
this.parentNode.getElementsByTagName("input")[0].checked =
false;
} else {
this.className = "posterImage selected";
this.parentNode.getElementsByTagName("input")[0].checked =
true;
}
});
Div.appendChild(Img);
var newCheckbox = document.createElement("input");
newCheckbox.setAttribute("type", "checkbox");
Div.appendChild(newCheckbox);
document.getElementById("idmain").appendChild(Div);
}
}
</script>
</body>
</html>