Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Why does my addEventListener function assign a value to a variable locally, but not globally?

I'm trying to write an app in Javascript, HTML and CSS, in which I take information from the user via input fields and save it to variables that are to be used later. I've assigned empty global variables at the beginning of the script, which are then supposed to be reassigned when event listener functions run. By logging to the console from inside and outside of the functions, I can see that the user input is being assigned to the variable within the function, but not outside of it.

Example code:

let inputName;

const person = document.getElementById('person');

function getName() {
  inputName = person.value;  
//if console.log(inputName) is here, the assigned value for inputName will be logged to the console
};

person.addEventListener('change', getName);
//if console.log(inputName) is anywhere outside of getName(), the value will not appear on the console

Plus the corresponding HTML:

<div>
   <label for='person'>What is your name?</label>
   <br>
   <input type='text' id='person' placeholder='John Doe' required>
</div>

I've tried all sorts of variations of this, but still haven't found the solution; any ideas as to how to fix/rewrite this?

question from:https://stackoverflow.com/questions/65903452/why-does-my-addeventlistener-function-assign-a-value-to-a-variable-locally-but

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay, I figured it out. Tempted to just delete the thread out of embarrassment, but will keep it up as I imagine I'm not the only newbie that gets blindsided by this sort of thing...

In a nutshell, having come to event listeners fairly recently, I neglected to take into account that the script will run substantially faster than I can enter a name into the input field, and thus will run the console.log() much earlier than I can hope to run the event listener function to assign a value, regardless of where I type console.log()... Facepalm! Anyway, it looks like @JakeAve called it - and I'll definitely remember to use setTimeOut() to get round this sort of thing in the future, that's a neat strategy.

Thanks everyone for taking your time to help out - much appreciated!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...