如何将数组生成为HTML

时间:2019-03-06 16:27:00

标签: javascript jquery html arrays json

所以,基本上,我的页面上有图像(每个图像都有一个类似的按钮),单击按钮后应显示在另一页上。

这是我将图像(单击它们的按钮后)放入数组的方式:

$('button').click(e => {
    let likedImgs= JSON.parse(localStorage.getItem('cart') || '[]');
    let itemName = $(e.target).data('name');
    let item = $('img').filter(v => v.name === itemName);

    likedImgs.push(item);
    localStorage.setItem('likedImgs', JSON.stringify(likedImgs));

});

在我喜欢的照片的页面上:

 <template>
                        <div id="isOutput"></div>
                </template>

这是我尝试将数组生成为HTML并将其作为图像显示在下一页上的方法:

  var myArr = JSON.parse(localStorage.getItem('likedImgs'));
                function  showContent () {
                  var temp, item, a, i;
                  temp = document.getElementsByTagName("template")[0];
                  item = temp.content.querySelector("div");
                  for (i = 0; i < myArr.length; i++) {
                    a = document.importNode(item, true);
                    a.textContent += myArr[i];
                    document.body.appendChild(a);
                  }
                }

但这似乎不起作用。你能告诉我我在做什么错吗?

控制台返回的对象数组如下所示:0:prevObject:0:{} 1:{} 2:{} 3:{} 4:{} 5:{} 6:{}长度:7 prevObject:{0:{…},长度:1} proto:对象proto:对象

1 个答案:

答案 0 :(得分:0)

stringify()不能很好地处理DOM元素。

  

Related Stack Question:如何使用JSON.stringify dom元素?

因此,我们需要从图像中拉出我们想要的属性并对其进行字符串化。

在此示例中,为简单起见,我使用隐藏输入来充当本地存储。

在按钮上单击,我们只是解析隐藏的字段,然后在result区域中重新创建元素

let likedImgs = [];
let itemName = '1'; //$(e.target).data('name');
let item = $('#source > img').filter((i, v) => v.name !== itemName); //changed the filter for demonstration
//only 'stringify' the properties that matter to me
likedImgs = $.map(item, x => {
  return {
    src: $(x).attr("src"),
    name: $(x).attr("name")
  };
});
//store them somewhere for example instead of localStorage//
$("#tst").val(JSON.stringify(likedImgs)); //replace with storing in localStorage
//localStorage.setItem('likedImgs', JSON.stringify(likedImgs));
//console.log($("#tst").val()); //output for prosperity



//handle a button click just for fun
$("button#p").click(x => show($("#tst").val())); //you will need to read from localStorage instead
//$("button#p").click(x => show(localStorage.getItem('likedImgs')));//like this

//process a json string, this function to be on page 2
function show(txt) {
  var txt = JSON.parse(txt);
  //var txt = JSON.parse(txt);
  var tmplate = $("#result");
  tmplate.empty(); //clean out the results//
  $.each(txt, function(i, elem) {
    tmplate.append($("<img>")
      .attr("src", elem.src)
      .attr("name", elem.name));
  });
}
div#source>img {
  border: 2px solid red;
}

img {
  height: 100px;
}

div#result>img {
  border: 2px solid green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id='p'>Process</button>
<div id='source'>
  <img src='https://picsum.photos/200/300/?random' name="1" />
  <img src='https://picsum.photos/200/300/?random' name="2" />
  <img src='https://picsum.photos/200/300/?random' name="3" />
  <img src='https://picsum.photos/200/300/?random' name="4" />
  <img src='https://picsum.photos/200/300/?random' name="5" />
</div>
<input id='tst' type='hidden' />
<!-- placeholder for localStorage -->
<div id="result"></div>