首页 > 解决方案 > 如何将所选图像的链接从数组存储到本地存储

问题描述

我正在寻找一种通过将索引存储在数组中来存储所选图像的方法。保存所选图像的索引并单击按钮(get item(带有id“完成”)后,我需要对数组中选择的图像进行字符串化,以便将它们存储在本地存储中。然后我需要提取数据从本地存储并将其转换回对象,将选定的图像写入页面,并从页面的本地存储中导入选定的图像。如果对数组的长度进行了更改,页面应该可以工作。

另外,我需要使用复选框来选择或取消选择该项目,但目前它仅在我单击图像时才起作用。谢谢!请只使用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>

标签: javascript

解决方案


推荐阅读