Jquery variable in function

In pageload, I set a variable

$(document).ready(function() { var inv_count = 3; }); 

When I try to reference this variable inside functions, this does not work.

 function blah(a,b) { alert (inv_count); } 

Why is this? And how can I get around this?

(rookie here)

+6
source share
2 answers

If you declare a variable inside a function, the variable name will not be available outside the scope of this function. Move the ad out of function:

 var inv_count; $(document).ready(function() { inv_count = 3; }); 
+11
source

You have a scope problem, I suggest you read a little about it, because you can improve your javascript per ton, but you can solve this in two ways:

 var inv_count; //you declare your variable in a global scope, it not very good practice $(document).ready(function() { inv_count = 3; }); function blah(a,b) { alert (inv_count); } 

or

 $(document).ready(function() { var inv_count = 3; function blah(a,b) { alert (inv_count); } //you declare everything inside the scope of jQuery, if you want to acess blah outside use: //window.blah = blah; }); 

I also recommend that you read clousures if you do not know how they work.

+12
source

Source: https://habr.com/ru/post/912524/


All Articles