JQuery makes a global variable

How to pass the value of the function a_href = $(this).attr('href'); into global a_href , do 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 
+13
javascript jquery
source share
3 answers

Your code looks great, except that if the variable declaration is inside the 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 a global variable, one solution is to declare the variable in the 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 should set the variable as a property of the window object

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

Why console printing is undefined

You get the output as undefined , because although the variable is declared, you did not initialize it with a value, the value of the variable is set only after the a element is pressed before this time the variable will be undefined . If you do not declare a variable, it will throw a ReferenceError

+33
source share

set the variable in the window:

 window.a_href = a_href; 
+3
source share

You can avoid declaring global variables by adding them directly to the global object:

 (function(global) { ... global.varName = someValue; ... }(this)); 

The disadvantage of this method is that global.varName will not exist until this particular line of code is executed, but this can be easily circumvented.

You can also consider the architecture of the application in which such global variables are contained in the closure, common to all functions that need them, or as properties of an accordingly accessible data storage object.

+3
source share

All Articles