【问题标题】:Functions not working when ```type="module"``` or import```type="module"``` 或导入时函数不起作用
【发布时间】:2021-04-08 12:25:02
【问题描述】:
import testBtn from '/functions.js'


window.onload = function() {
    document.getElementById('questions1').style.display = 'block'
    document.getElementById('questions2').style.display = 'none'
    document.getElementById('questions3').style.display = 'none'
    document.getElementById('questions4').style.display = 'none'
    document.getElementById('questions5').style.display = 'none'
}

function nextQuestion() {
testBtn("hello")
}

当我尝试导入或将脚本类型更改为 type="module" 时,所有函数都不起作用,当所有脚本类型都没有导入或更改时,该函数起作用,并且我收到以下错误 - Uncaught ReferenceError: nextQuestion is not defined at HTMLButtonElement.onclick

【问题讨论】:

  • 这能回答你的问题吗? ES6 module scope
  • 不抱歉,我在尝试实现此功能时遇到了麻烦。我试图将 javascript 模块加载到实际的按钮输入中,并尝试查看 src="js 文件" 是否可以工作,但我没有任何运气。我要做的就是从该javascript变量中导入变量,因为变量将具有来自先前问题的回答问题的值。所以我只需要将该变量真正导入到下一个 html 页面并显示计算

标签: javascript function import


【解决方案1】:

ECMAScript 模块不使用全局范围,因此 HTML 元素上的 onclick="nextQuestion" 属性将无法找到 nextQuestion,因为它不在全局范围内,而是在模块范围内(与 @987654323 一起使用时) @)。要解决此问题,请将 nextQuestion 函数放入全局范围:

window.nextQuestion = function() {
  testBtn("hello")
}

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-27
    相关资源
    最近更新 更多