javascript - Uncaught SyntaxError: Unexpected token { 导入数组时
问题描述
我正在为一堂课做一个应用程序,教授和我一样困惑为什么它不起作用。我有 2 个 js 文件和 1 个 html。我正在将一个数组从一个 js 导出到另一个,然后将该 js 用作我的 html 中的 src。这是相关的代码:
medList.js:
export const CompleteMedList = [
.....
];
主.js:
import {CompleteMedList} from './MedList.js'
html:
<script src="main.js"></script>
这是我得到的错误:
main.js:1 Uncaught SyntaxError: Unexpected token {
我尝试在脚本标记中使用 type="module",但是当我尝试使用 main.js 中声明的函数执行操作时,它给了我这个错误:
未捕获的 ReferenceError:openCycleForm 未在 HTMLButtonElement.onclick 中定义
这是 main.js 中错误引用的函数:
function openCycleForm() {
document.getElementById("newCyclePg1").style.width = "100%";
for (var i=0; i < CompleteMedList.length; i++){
document.getElementById("fullMedsList").innerHTML +=
"<input type=\"checkbox\" name=\"meds\" id=\"" + CompleteMedList[i].id + "\">" +
CompleteMedList[i].name + "<br></br>";
}
}
I initially had the code in the html file (where it worked), but just moved it to main.js so I could use an array of data instead of hardcoding it, and then everything broke...
解决方案
It looks like it's being a bit funny with the inline JS, so I suggest you remove it and add the event listeners in main.js
instead. Something like this which I have working locally on my machine at the moment:
HTML
<button type="button" class="currentCycle">Current Cycle</button>
JS
const currentCycleButton = document.querySelector('.currentCycle');
currentCycleButton.addEventListener('click', openCurrentCycle, false);
function openCurrentCycle() {
document.getElementById("currentCycle").style.width = '100%';
console.log('done');
}
推荐阅读
- javascript - React/React Context API:使用 useEffect() 钩子时等待上下文值
- google-api - 无法为测试 G Suite 市场项目触发全域安装
- python - 我想将这些输出转换为列表
- push-notification - FCM - 为什么在较新的 Firebase Admin SDK 中不再支持 FCM 直接通道?
- php - 如何在 laravel DB::select 查询中传递 foreach
- jtag - Trace32:如何使用 t32apinet 以编程方式获取维护密钥到期月份和年份?
- or-tools - 如何在 OR-Tools Routing Solver 中实现自定义软约束?
- python - 使用 .loc 的 Pandas 数据框分配因 MultiIndex 而失败
- javascript - 无法从 div 获取数据
- salt-stack - 如何从 Master 修改 Salt Minion 配置文件中的默认选项