This question has already been answered:

There are several elements with the class .q1, each has a variable "a" with a value of 1. How to make so that when you click on one of the elements with the class .q1, all the other variables "a" change the value to 0. Has it not changed in the pressed?

I tried this: ˅

$('.q1').each(function() { var a = 1; $(this).click(function() { $('.q1').a = 0; }); }); 

Reported as a duplicate at Grundy. javascript Feb 13 '17 at 6:30 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 3
    How can elements have a variable? - user207618
  • The each () loop goes through all the .q1 elements. In the anonymous function of each element there is a variable "a", isn't it? - PeGaS
  • 2
    Each time you create a new variable ( var a = ), which is destroyed after the function ends. - user207618
  • @Other How is it destroyed? if you trigger a click event once, one action will work, and when pressed again, another $ ('. q1'). each (function () {var a = 1; $ (this) .click (function () {if ( a! = 0) {// one action a = 0;} else {// another action a = 1;}});}); - PeGaS
  • one
    @NickVolynkin, I'm not upset, help and comments - help. - user207618

1 answer 1

The variable you created in the anonymous function will remain inside the anonymous function. You need to contact through just a .

Please read the entire section.
Scope and closures