-1

I am new to ajax and it is the first time I am using the jQuery's load() method. The example bellow doesn't work. The variable inside doSomething() is not defined (because of the asynchronously call I guess)

var x = jQuery("#div1 a"); // x is used in different parts of the code, not only for the doSomething function 

jQuery('.test').load(homeUrl, function() {
    doSomething();
};

function doSomething () {
     x.css('background-color', 'yellow');
}

So, I am doing like this (which is repetitive) and it works:

function doSomething () {
    var x =  jQuery("#div1 a");
    x.css('background-color', 'yellow');
}

But I would like to know if there is a better way of dealing with the variable or even if I am doing something wrong.

viery365
  • 935
  • 2
  • 12
  • 30

1 Answers1

1

You could pass x to the doSomething function like so:

var x = jQuery("#div1 a");

jQuery('.test').load(homeUrl, function() {
    doSomething(x);
};

function doSomething(x) {
    x.css('background-color', 'yellow');
}
Brad
  • 8,044
  • 10
  • 39
  • 50
  • Thank you!:) This is a good idea, but inside that function in reality I have lots of variables that are already defined before and in this situation I would have to use lots of parameters (I guess?). – viery365 Nov 30 '16 at 16:46