How can I loop through objects and append it's values to a webpage

问题: Aim: I'm creating a two page website with the homepage a static page and the other a dynamic page. I have a number of buttons on the homepage. I also have a list of objects...

问题:

Aim: I'm creating a two page website with the homepage a static page and the other a dynamic page. I have a number of buttons on the homepage. I also have a list of objects and I want to loop through each list and append it to each button so that on button click the values of the object will display on the dynamic page.

Here are my codes.

HTML. Homepage

<div>
     <p>USA</p>
    <Input type="button" value="View Flag" />
     <p>EU</p>
     <Input type="button" value="View Flag" />
</div>

Dynamic Page

<div>
   <div class="flag"></div>
</div>

JavaScript/jQuery

//Objects 
var usFlag ={
     name: "USA flag",
     imgURL: "https://photos.com/usa.jpg"
 }

 var euFlag ={
     name: "EU flag",
     imgURL: "https://photos.com/eu.jpg
 }
 $(.'flag').append('<IMG src=' + imgURL+ ' />);

so I want that when I click on USA flag button, the dynamic page will show USA flag and vice versa.

Thank you


回答1:

Just store particular data in localStorage onclick and redirect to another page where you can get that data

<div>
  <p>USA</p>
  <Input type="button" value="View Flag" onclick="setDetails('usFlag')" />
  <p>EU</p>
  <Input type="button" value="View Flag" onclick="setDetails('euFlag')" />
</div>


    function setDetails(data) {

      var usFlag = {
        "name": "USA flag",
        "imgURL": "https://photos.com/usa.jpg"
      };

      var euFlag = {
        "name": "EU flag",
        "imgURL": "https://photos.com/eu.jpg"
      };

      if (data == 'usFlag') {
        localStorage.a = JSON.stringify(euFlag);
        console.log(localStorage.a);

      } else if (data == 'euFlag') {
        localStorage.a = JSON.stringify(euFlag);
        console.log(localStorage.a);
      }

     window.location = "dynamicpage.html";
    }

回答2:

If those those divs are on the same page you can do this,

<div>
     <p>USA</p>
    <Input type="button" id="usa_button" value="View Flag" />
     <p>EU</p>
     <Input type="button" id="eu_button" value="View Flag" />
</div>
<div>
   <div class="flag"></div>
</div>
</a>
<script> 
//Objects 
var usFlag ={
     name: "USA flag",
     imgURL: "https://photos.com/usa.jpg"
 }

 var euFlag ={
     name: "EU flag",
     imgURL: "https://photos.com/eu.jpg"
 }  
jQuery('#usa_button').on('click',function(){
    jQuery('.flag').html('<img src="'+usFlag.imgURL+'">')
})
jQuery('#eu_button').on('click',function(){
    jQuery('.flag').html('<img src="'+euFlag.imgURL+'">')
})
</script>
  • 发表于 2019-03-18 05:57
  • 阅读 ( 167 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除