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
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.
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.
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.
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
set the variable on window:
window.a_href = a_href;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With