Function variable need to use in another function

Hello Folks,

How can i use one function variable in another function, I heard that we can do it by closure but my scenario is like below:

$(document).on('click','.btn1', function(){
		var test = value1;//values
			}
					
	$(document).on('click', '.btn2', function(){
		$('.myDiv').text(test.name);// it will throwing error 'test is not defined
		}

Currently I am making the variable ‘test’ to global so that we can use, is there any better way.

Don’t define the variable inside the first function, define it outside, and both functions will be able to access it.

This is different from being a global variable, for the variable is defined within the scope of some other function, in this case the jQuery() function.

For example:

jQuery(function ($) {
    var test;
    $(document).on('click','.btn1', function(){
        test = value1; // values
    });
    					
    $(document).on('click', '.btn2', function(){
        $('.myDiv').text(test.name);
    });
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.