开发者

Cached Jquery selector behavior that I do not understand

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 ea开发者_如何学运维ch 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!

$(function() {
  // your code
});

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.


Just to improve on the previous answer - b is only evaluated when you call the Test function, probably once the page is loaded. Cache the selectors inside document ready:

 $(document).ready(function(){
   var a = $('#foo');
 });

I only cache selectors when I'm using the same selector inside a block of code. I use the $variable naming convention for this:

var $divs = $('div');

You can also chain functions together to avoid having to cache the selector:

$('div').append('hello world').addclass('hello').show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜