简体   繁体   English

如何使用 Javascript 循环遍历数组并更改和添加额外的 HTML,以输出带有这些值的一些文本?

[英]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.例如,我正在使用一个返回 JSON 值数组的 API,并且我想将它们输出到页面。

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:我为单击按钮时要输出的值的布局创建了一些 HTML,如下所示:

<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);我通过执行以下操作附加从 API 检索到的值: 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]).这可以输出第一个事务所需的值(索引 [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?我如何创建一个循环,该循环基本上在开始时使用模板 HTML,然后将其输出到数组中的下 5 个元素,以便它成为以相同格式输出的每个新事务的详细信息,但无需编码5次?

I'm new to HTML and Javascript so appreciate any help.我是 HTML 和 Javascript 的新手,非常感谢任何帮助。 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.第一条建议,如果您还不知道,如果您打算将静态 id 用于显示列表,则应避免在 html 模板中使用静态 id,因为 id 在单个 html 页面中必须是唯一的。

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.如果你知道著名的如 Angular 或 React。 You can also use jQuery as someone has advised you.您也可以按照某人的建议使用 jQuery。

Here is a little example with VueJS which allows you to define components with html templates.这是一个 VueJS 的小例子,它允许您使用 html 模板定义组件。 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) :然后,您可以使用 for 指令在循环中使用它们(请注意,我不是 VueJS 专家,您可能会找到更好的解决方案):

<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 :用于示例的文档:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 HTML 获取输入,然后使用这些输入与 javascript 运行循环? - How do I take inputs through HTML and then use those to run a loop with javascript? 如果javascript / html中的其他一些值更改,如何更改值的数组? - How can I change my array of values if some other value changes in javascript/html? JavaScript-当两个值相同时,如何使用打印功能输出存储在数组中的2个值? - JavaScript - How can I use the print function to output 2 values that are stored in an array when those values are the same? 如何在javascript中使用for循环来添加HTML - How can i use a for loop in javascript to add HTML 如何在JavaScript中遍历此数组? - How can I loop through this array in javascript? Javascript-如何遍历中继器中的控件并找到某些下拉列表的值 - Javascript - How can I loop through the controls in a repeater and find the values of some dropdown lists JavaScript:如何正确遍历数组并将值用作键? - JavaScript: How to properly loop through array and use values as keys? 如何在从 html 集合创建的数组中通过 for 循环从对象中获取元素的值? - How can I get values of elements from objects through for loop in an array created from a html collection? 如何使用 for 循环遍历数组值? - How to use a for loop to loop through array values? 如何在每个循环中保存变量的值,以便以后可以使用这些值 - How do I save the value of a variable on each loop so I can use those values later
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM