我试图创建一个从用户输入接收的全局变量,并将其用于各种事件侦听器中,但是我无法从事件侦听器的回调函数外部访问该变量。
函数不应该访问在其父函数上下文中声明的变量吗?
window.addEventListener('load', function(){
/* ---- User Input ---- */
const userInput = document.querySelector('.userInput').value;
const userInputArr = userInput.split(' ');
document.querySelector('.btn').addEventListener('click', function() {
/* function's code */
console.log(userInputArr);
});
};
它工作的唯一方法是当我在回调函数内部创建const变量时。
我糊涂了。