Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery make global variable

How to pass function a_href = $(this).attr('href'); value to global a_href, make a_href="home"

var a_href;       $('sth a').on('click', function(e){         a_href = $(this).attr('href');            console.log(a_href);            //output is "home"          e.preventDefault();     }  console.log(a_href);   //Output is undefined  
like image 860
olo Avatar asked Sep 25 '13 03:09

olo


People also ask

How do you declare a global variable in jQuery?

Note that we can declare a global variable in two ways, the first way is declaring a variable outside a function, and the second way is to assign a value to the variable without using a var keyword inside a function that means the variable automatically becomes a global variable.

How do you create a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do I create a global function in JavaScript?

Everything in JS is bound to containing scope. Therefore, if you define a function directly in file, it will be bound to window object, i.e. it will be global. To make it "private", you have to create an object, which will contain these functions.


2 Answers

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){     //here it is a closure variable     var a_href;     $('sth a').on('click', function(e){         a_href = $(this).attr('href');            console.log(a_href);            //output is "home"          e.preventDefault();     } }) 

To make the variable global, one solution is to declare the variable in global scope

var a_href; jQuery(function(){     $('sth a').on('click', function(e){         a_href = $(this).attr('href');            console.log(a_href);            //output is "home"          e.preventDefault();     } }) 

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href') 

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

like image 171
Arun P Johny Avatar answered Sep 20 '22 13:09

Arun P Johny


set the variable on window:

window.a_href = a_href; 
like image 27
gp. Avatar answered Sep 21 '22 13:09

gp.