Variable control with Javascript for html

3

I have an HTML code with JavaScript that when clicking on top; If x == 1 , it executes task A and variable arrow javascript x = 0 , otherwise it executes task B and variable arrow javascript x = 1 , however variable is restarted whenever function is started.

How to resolve?

JavaScript:

function toogle_m(MID, PID) {
    if(x == 1) {
        alert("Luck 7!"+"x");
        var x = 0;
    } else {
        alert("You're not very locky today..."+"x");
        var x = 1;
    }

    $(MID).fadeToggle(500);
    $(PID).hide();
}

HTML:

<div class="F1" onclick="toogle_m(del)">
    <img src='resources/images/andremachado/del.png' width='25' title='Excluir insumos'/>
</div>

I know it will restart because the function is always started, but what is the solution?

    
asked by anonymous 07.12.2015 / 13:25

2 answers

5

Your problem is in the scope in which the variable was declared. If you declare a variable within the function, its lifetime will be equivalent to that of the function. One way to get around this is by declaring the variable outside the function, it looks like this:

// Inicializa com 0.
var x = 0;

function toogle_m(MID, PID) {
    if(x == 1) {
        alert("Luck 7!"+"x");
        x = 0;
    } else {
        alert("You're not very locky today..."+"x");
        x = 1;
    }

    $(MID).fadeToggle(500);
    $(PID).hide();
}
    
07.12.2015 / 13:34
3

Try this, making X your global variable.

var foo = 0;
function toogle_m(){
    if (foo == 1) { 
        alert("Lucky 7!"+"x");
    foo = 0;
  }
  else{
    alert("You're not very lucky today..."+"x"); 
    foo = 1;
  }

}

$(document).ready(function(){
    $('.F1').click(function(){
      toogle_m();      
    });
});

Html

<div class="F1">
    <img src='resources/images/andremachado/del.png' width='25' title='Excluir insumos'/>
</div>

Example

jsFiddler

    
07.12.2015 / 13:38