javascript - 如何将数组从 .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>
当我只是将数组复制并粘贴stocks
到stocks.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"
}
}
解决方案
当您将数组导出为 CJS 模块时,我建议您查看CommonJS (CJS) 模块文档
此外,在您的情况下,您可以只需要您的 stock.js 正在导出的模块。像这样:
const { stocks } = require('path/to/socks.js')
推荐阅读
- flutter - 我可以扩展 State 类并覆盖 setState
- c++ - 在 VTK 项目中配置 CMake 时如何解决此错误
- python - 如何根据列值对数据集进行采样?
- firebase - Firestore 规则、查询和结构化数据
- python - 为什么 Python 类方法中没有打印 f 字符串?
- c# - Xamarin MultiBinding 需要来自更高祖先级别的 BindingContext 或 XAML 树中的命名项
- android - 导航组件 - 仅限 Activity 中的 ActionBar 句柄
- javascript - 重定向后如何显示警报指示器?
- linux - 为 linux mint 20 构建 mono-complete 4.6.2
- c++ - 我们如何生成一定数量的随机数并将它们相互链接,而无需将数字链接到自身?