There are three links:

<div class="menu"> <a href="#" id="one" onclick="engine()">Rock</a> <a href="#" id="two" onclick="engine()">Paper</a> <a href="#" id="three" onclick="engine()">Scissors</a> 

The task, when clicking on one of the links, is to change (set) the value in the global variable userChoice.

 var userChoice; // глобальная переменная function engineGame() { // ее вызываем при клике на ссылку document.getElementById('one').onclick = function() { userChoice = "rock"; alert("до вызова функции userChoice = " + userChoice); // rock } document.getElementById('two').onclick = function() { userChoice = "paper"; alert("до вызова функции userChoice = " + userChoice); // paper } document.getElementById('three').onclick = function() { userChoice = "scissors"; alert("до вызова функции userChoice = " + userChoice); //scissors } }; engineGame(); alert("после вызова функции userChoice = " + userChoice); // сразу выскакивает undefined :( 

Question: 1. Have I achieved the task? (set the value in a global variable) or is it done differently?

  • That's right, it is clear that undefined, the event has not yet been executed so that the variable would be reassigned. - Redr01d
  • alert inside onclick transfer - Jean-Claude
  • those. after I clicked on the link and until the page was reloaded, was the variable assigned a value according to the program? Or ask differently, did I correctly set the value in the global variable on click? - Evgeny
  • Make another link <a href="#" id="three" onclick="alert(userChoice)"> Test </a> and check. But it seems to be correct. - Maxim Drobyshev
  • one

1 answer 1

The code is correct only if events are assigned after the download of the reference code. Event assignments are best done in the body of the onload of the window's onload event. It is also better to use the addEventListener function in case this is not the only event by reference:

 var userChoice = null; window.addEventListener("load", function() { document.getElementById("one").addEventListener("click", function() { userChoice = "rock"; alert(userChoice); }); document.getElementById("two").addEventListener("click", function() { userChoice = "paper"; alert(userChoice); }); document.getElementById("tree").addEventListener("click", function() { userChoice = "scissors"; alert(userChoice); }); }; 
It is even better to make a GameEngine object and store the user's choice in his field without breeding global variables, especially with such a simple name.