"Cannot read property ClassList of Undefined" 将 Javascript 移动到模块后出错
"Cannot read property ClassList of Undefined" error after moving Javascript into modules
我是 JS 的新手,在尝试将一些 JS 分成模块时 运行 遇到了问题。我认为这是一个简单的修复,但我希望这里有人可以帮助我朝着正确的方向前进。如果我只是将它全部放入一个 JS 文件中,然后通过标记直接使用 index.html link,我的代码工作正常,所以从移动到模块时出现了一些问题。
在我的 HTML 中,我有几个元素会根据用户在网站上单击的按钮改变可见性。在我尝试将其放入模块之前,原始脚本文件中编写的 JS 运行良好:
showHideSections = (section) => {
if (section.classList.contains("hidden")){
section.classList.remove("remove-tab");
section.classList.remove("slideout");
... };
所以,我在代码的开头添加了 export const 以将其导出到 main.js 文件:
export const showHideSections = (section) => { ...
然后导入到main.js:
import { ..., showHideSections, ... } from "./modules/script.js"
window.addEventListener("DOMContentLoaded", () => {
...
showHideSections();
... });
现在我遇到了 Uncaught TypeError: cannot read 属性 "ClassList" of undefined.
我猜这与代码的顺序有关 运行 既然 JS 已经移入了一个模块,但是经过几次尝试以不同的方式执行代码之后,我感觉卡住了。我已经尝试调整 main.js 上的 addEventListener 以在“加载”与 DOM 内容加载时执行。我也曾尝试为 script.js 文件中的元素创建一个对象作为解决方法,但那里也没有骰子。
有什么想法吗?
嗯,看来你没有在方法调用中传递 section 参数:
import { ..., showHideSections, ... } from "./modules/script.js"
window.addEventListener("DOMContentLoaded", () => {
const section = document.querySelector("#someSelectorHere");
showHideSections(section);
});
我是 JS 的新手,在尝试将一些 JS 分成模块时 运行 遇到了问题。我认为这是一个简单的修复,但我希望这里有人可以帮助我朝着正确的方向前进。如果我只是将它全部放入一个 JS 文件中,然后通过标记直接使用 index.html link,我的代码工作正常,所以从移动到模块时出现了一些问题。
在我的 HTML 中,我有几个元素会根据用户在网站上单击的按钮改变可见性。在我尝试将其放入模块之前,原始脚本文件中编写的 JS 运行良好:
showHideSections = (section) => {
if (section.classList.contains("hidden")){
section.classList.remove("remove-tab");
section.classList.remove("slideout");
... };
所以,我在代码的开头添加了 export const 以将其导出到 main.js 文件:
export const showHideSections = (section) => { ...
然后导入到main.js:
import { ..., showHideSections, ... } from "./modules/script.js"
window.addEventListener("DOMContentLoaded", () => {
...
showHideSections();
... });
现在我遇到了 Uncaught TypeError: cannot read 属性 "ClassList" of undefined.
我猜这与代码的顺序有关 运行 既然 JS 已经移入了一个模块,但是经过几次尝试以不同的方式执行代码之后,我感觉卡住了。我已经尝试调整 main.js 上的 addEventListener 以在“加载”与 DOM 内容加载时执行。我也曾尝试为 script.js 文件中的元素创建一个对象作为解决方法,但那里也没有骰子。
有什么想法吗?
嗯,看来你没有在方法调用中传递 section 参数:
import { ..., showHideSections, ... } from "./modules/script.js"
window.addEventListener("DOMContentLoaded", () => {
const section = document.querySelector("#someSelectorHere");
showHideSections(section);
});