Why can't I set this element reference as a variable?
I have a javascript object as such (simplified).
var MyObject = (function(){
var propertyOne = $('.links li:first-child');
var propertyTwo = $('.links .active');
function startup()
{
propertyOne.addClass("class"); //Works
propertyTwo.addClass("class2"); //Does not work
$('.links .active').addClass("class2"); // W开发者_StackOverfloworks
}
return {
init: function()
{
startup();
}
}
});
What's the difference in the way I'm selecting propertyOne and propertyTwo? I don't understand why
propertyOne.addClass("class"); //Works
$('.links .active').addClass("class2"); // Works
Yet...
propertyTwo.addClass("class2"); //Does not work
Can anyone help explain this to me?
The DOM element for propertyTwo must not exist at the time that var propertyTwo = $('.links .active')
is called, whereas it does once startup()
is called.
To confirm this, we'll need more information about your script. For example, what I previously described could occur if MyObject
is created prior to the DOM being fully loaded, and then you call the init()
method after the DOM is fully loaded (or at least after the element corresponding to $('.links .active')
has been loaded.
Regardless, you should really focus on learning how to debug something like this along with why this specific attempt is not working. The main step in this process is to log to the console propertyTwo
right after the line var propertyTwo = $('.links .active')
. If the console shows []
(in Chrome at least), that means no elements were matched, which would support what I said is happening.
精彩评论