Why are things wrong?



  • Good day, everyone. There's a mission: Record the list. The communication has the following data from the sender, the date and time of the communication and the body. Describe the date and time and the sender on the list. By ordering the sender to take the message. Message download. Everyone's been drinking, except for a point of introduction. In my mind, every element with a name is subject to a function that adds or removes the class .visible to the relevant element with the message. The problem is, somehow, a toggleMessage(i) is transmitted i=3. I don't understand why and how to make it work properly.

     function toggleMessage (counter) {
        messages[counter].classList.toggle("visible");
    }
    for (var i = 0; i < names.length; i++) {
        names[i].onmouseover = function(){ toggleMessage(i) };
        names[i].onmouseout = function(){ toggleMessage(i) };
    }
    

    Full code here: https://jsfiddle.net/x6rf5bq8/3/



  • Because at the time of performance toggleMessage(i) cycle completed and i equal to the maximum value - names.length♪ We need to create a lock:

    for (var i = 0; i < names.length; i++)(function(i) {
        names[i].onmouseover = function(){ toggleMessage(i) };
        names[i].onmouseout = function(){ toggleMessage(i) };
    }(i));
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2