在我的app.js文件中,我做了很多document.getElementById(‘某些元素’)调用。我认为将此调用的结果存储到一个变量中,然后在需要时通过它访问元素会更具可读性和可维护性。在vanilla JS中执行此操作的常用方法是什么,以便它们在所有函数中都可用?我需要创建全局变量吗?
发布于 2021-11-21 04:48:40
只需在代码的顶层将其设置为一个变量
const someElement = document.getElementById('some-element');
function firstFunction () {
// access by using 'someElement'
}
function secondFunction () {
// access by using 'someElement'
}
https://stackoverflow.com/questions/70051337
复制相似问题