Given the following code why am I getting different values for a and b? I would have thought they would return the same thing:
(function() {
var a = $('#foo');
var Test = function(){
console.log(a); //outputs 'jQuery()'
var b = $('#foo');
console.log(b); //outputs 'jQuery(select#foo)' which is what I want
};
})();
This question stems from me trying to stick frequently used selectors into vars. Originally I was doing it in each method (like I did with var b in the above example) but then I found I needed to use the selectors in multiple methods so I moved the assignment out to be available (or so I thought) to all of the methods in that anonymous function. As you can see, it does not work. Why is this?
EDIT: this code is loaded by a method that is triggered by a click. The id foo is present at page load and is not dynamically set or changed.
Make sure that the code isn’t called until after your page finishes loading!
Also, of course, you’ll want to be careful about caching things that might be changed on the page by other parts of your client-side application.