简体   繁体   中英

How Can I use Javascript to loop through an array and change and add extra HTML that outputs some text with those values?

For Example, I am using an API that returns an JSON array of values and I want to output them to the page.

Here is the full code I am working with if anyone wants to try it out to see where I can get it to work.

I have created Some HTML for the layout of the values I want to output when a button is clicked like so:

<p class="txData"> 
    <p id="txHash">Transaction ID: </p><br>
    <p id="txTime">Time: </p><br>
    <p id="txToken">Token Symbol: </p><br>
    <p id="txTo">To: </p><br>
    <p id="txFrom">From: </p><br>
    <p id="txValue">Amount Transferred: </p><br>
    <p>***********************************</p><br>
</p>

I then assign variables for those elements which I want to append to:

        let txHash = document.querySelector('#txHash');
        let txTime = document.querySelector('#txTime');
        let txToken = document.querySelector('#txToken');
        let txTo = document.querySelector('#txTo');
        let txFrom = document.querySelector('#txFrom');
        let txValue = document.querySelector('#txValue');

And I append the retrieved values from the API by doing: txHash.insertAdjacentHTML('beforeend', jsonFile.result[0].hash);

                txTime.insertAdjacentHTML('beforeend', jsonFile.result[0].timeStamp);

                txToken.insertAdjacentText('beforeend', jsonFile.result[0].tokenSymbol)

                txTo.insertAdjacentHTML('beforeend', jsonFile.result[0].to);

                txFrom.insertAdjacentHTML('beforeend', jsonFile.result[0].from);

                txValue.insertAdjacentHTML('beforeend', web3.utils.fromWei(jsonFile.result[0].value, 'ether'));

This works to output the values wanted for the first Transaction (index [0]).

How could I create a loop that would basically use the template HTML at the start but then output it for the next 5 elements in the array so that it would be the details for each new trasanction outputted in the same format, but without having to code it 5 times?

I'm new to HTML and Javascript so appreciate any help. Thank you.

First piece of advice, if you don't already know it, you should avoid using static id's in your html template if you plan to use it for displaying a list, because id's must be unique in a single html page.

Second one, you should use a framework to help you displaying your data as a list. If you know famous ones such as Angular or React. You can also use jQuery as someone has advised you.

Here is a little example with VueJS which allows you to define components with html templates. Then, you can use them in a loop with the for directive (please note I'm not a VueJS expert and you may find better solutions) :

<body>
    <div id="app">
      <div v-for="json in jsonFile">
        <data-display v-bind:json="json"></data-display>
      </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript">
      
      var DataDisplay = {
        props: ['json'],
        template: '<div class="txData">\
                    <p>Transaction ID: {{json.hash}}</p>\
                    <p id="txTime">Time: {{json.timeStamp}}</p>\
                    <p id="txToken">Token Symbol: {{json.tokenSymbol}}</p>\
                    <p id="txTo">To: {{json.to}}</p>\
                    <p id="txFrom">From: {{json.from}}</p>\
                    <p id="txValue">Amount Transferred: {{json.value}}</p>\
                    <p>***********************************</p>\
                   </div>'
      };
      
      var vm = new Vue({
        el: "#app",
        data: {
          jsonFile: [
            {
              hash: 'hash1',
              timeStamp: 'timestamp1',
              tokenSymbol: 'token1',
              to: 'to1',
              from: 'from1',
              value: 'value1'
            }, {
              hash: 'hash2',
              timeStamp: 'timestamp2',
              tokenSymbol: 'token2',
              to: 'to2',
              from: 'from2',
              value: 'value2'
            }
          ]
        }, 
        components: {
          'data-display': DataDisplay
        }
      });
    </script>
  </body>

Documentation used for the example :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM