简体   繁体   中英

How do I console.log the result of a foreach loop with a 'click' function?

Apologies if this is really simple but I have been researching this for a week now but can't find the right thing to type into google.

I have 3 buttons as shown below:

 const playerSelection = document.querySelectorAll(".buttons").forEach(e => { e.addEventListener('click', function() { return e.innerHTML; }) }); console.log(playerSelection);
 <div> <button class="buttons">Rock</button> <button class="buttons">Paper</button> <button class="buttons">Scissors</button> </div>

When I console.log playerSelection it only returns undefined. I want the playerSelection variable to equal the innerHTML content of whichever button I click.

Help is appreciated.

You log the value of the button inside the click event.

Also you should set the type of your buttons to button , otherwise they are of type submit , which I guess you don't want here.

 document.querySelectorAll(".buttons").forEach(e => { e.addEventListener('click', function() { console.log(e.innerHTML); }) });
 <div> <button type="button" class="buttons">Rock</button> <button type="button" class="buttons">Paper</button> <button type="button" class="buttons">Scissors</button> </div>

You're probably thinking of Array.prototype.map , which combines the returned results into an array.

This won't work in your case, though, as you are simply adding an event listener inside your loop. The event callback will only be triggered when the button is clicked. You'll need to write asynchronous code. For example, when a button is pressed, call a function pickedValue() with the result, which will then continue your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM