首页 > 解决方案 > 如何将数组从 .js 文件导入 HTML 文件?

问题描述

我是 JS 和 HTML 的新手,对于一个作业,我得到了stocks.js一个包含数组的内容:

'use strict';

const stocks = [
    { company: 'Splunk', symbol: 'SPLK', price: 137.55 },
    { company: 'Microsoft', symbol: 'MSFT', price: 232.04 },
    { company: 'Oracle', symbol: 'ORCL', price: 67.08 },
    { company: 'Snowflake', symbol: 'SNOW', price: 235.8 },
    { company: 'Terradata', symbol: 'TDC', price: 44.98 }
];

module.exports.stocks = stocks;

我应该在我制作的另一个静态 HTML 页面中使用这个数组stocklist.html,来制作一个包含所有数据的表格stocks.html。到目前为止,我有:

<html lang = "en">
    <head>
        <meta charset = "utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
        <table>
            <caption><h1>Stock List</h1></caption>
            <thead>
                <tr>
                    <th>Company |</th>
                    <th>Symbol |</th>
                    <th>Cost</th>
                </tr>
            </thead>
            <tbody id = "stockTable">

            </tbody>
        </table>

        <script>
            const { stocks } = require('./stocks.js');
            buildTable(stocks);
    
            function buildTable(data) {
                var table = document.getElementById("stockTable")
    
                for (var i = 0; i < data.length; i++) {
                    var row = 
                        `<tr>
                            <td>${data[i].company}</td>
                            <td>${data[i].symbol}</td>
                            <td>${data[i].price}</td>
                        </tr>`
                    table.innerHTML += row;
                }
            }
        </script>
    </body>
</html>

当我只是将数组复制并粘贴stocksstocks.js元素<script>中时,表格就创建好了。但是,鉴于作业的要求,我不能这样做,我也不能编辑stocks.js. 如何将stocks数组从stocks.js导入到stocklist.html,以便我可以访问buildTable

编辑:我的不可编辑的 package.json 文件是为我分配的。

{
  "name": "assignment3",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.12"
  }
}

标签: javascripthtmlarrayshtml-table

解决方案


当您将数组导出为 CJS 模块时,我建议您查看CommonJS (CJS) 模块文档

此外,在您的情况下,您可以只需要您的 stock.js 正在导出的模块。像这样:

const { stocks } = require('path/to/socks.js')

推荐阅读