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
631 views
in Technique[技术] by (71.8m points)

event listener - How do I get the variable value outside of EventListener function in Javascript?

I have this code where I want to access the variable value outside the EventListener function to capture which button was clicked so that I can show a modal window with the relevant button value. Please help.

Here, in the code below, I want to assign value to the variable wordClicked.

const btn1OpenModal = document.querySelector(".word-one");

const btn2OpenModal = document.querySelector(".word-two");

const btn3OpenModal = document.querySelector(".word-three");

const btn4OpenModal = document.querySelector(".word-four");

export let wordClicked;

btn1OpenModal.addEventListener("click", function () {
  openModal();
  wordClicked = "firstWord";
});

btn2OpenModal.addEventListener("click", function () {
  openModal();
  wordClicked = "secondWord";
});

btn3OpenModal.addEventListener("click", function () {
  openModal();
  wordClicked = "thirdWord";
});

btn4OpenModal.addEventListener("click", function () {
  openModal();
  wordClicked = "fourthWord";
});
question from:https://stackoverflow.com/questions/65952537/how-do-i-get-the-variable-value-outside-of-eventlistener-function-in-javascript

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

1 Reply

0 votes
by (71.8m points)

You can't export a variable, only a value.

At the time you export the value of wordClicked, that value is undefined.

You can't change the exported value later.


You could export an object and then later change a property of that object, but likely you will need to make the event listener functions themselves responsible for opening the model.


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

...