gpt4 book ai didi

javascript - 当 `` `type ="module"``` 或 import 时函数不工作

转载 作者:行者123 更新时间:2023-12-02 16:20:55 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于javascript - 当 `` `type ="module"``` 或 import 时函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65533391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com