首页 > 解决方案 > 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...

标签: javascript

解决方案


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');
}

推荐阅读