In a javascript program there is an array (gData) that contains objects.
Each of these objects has a property called label that is an object.
each label contains a span called span_ within a div called div_.
Amongst other gData related operations, the label object is instantiated as
gData.label = new Label();
and then the gData object is pushed onto the gData array.
In the main program, i can execute the following jquery code that works fine:
$(gData[0].label.span_).css("border","5px solid green");
I want to add a function prototype to the label object called setCSS(). I would call the setCSS method like this:
gData[0].label.setCSS("border","5px solid green");
The setCSS code that I wrote (below) does not work. I’m guessing that the selector isn’t working.
Label.prototype.setCSS = function(args) {
// args contains an object in the form {"cssAtribute":"cssData"}
// call this method as label.setCSS({"border":"3px solid blue"});
// Any number of css attributes can be included in the args object
$.each(args, function(theKey, theValue) {
$(this.span_).css(theKey, theValue);
});
}
I’ve tried $(this.span_), $(this.div.span_) and several other selectors, none work.
Using Firebug I can see that gData[0] contains a label object and the label object contains a span_ object. Is my selector specification wrong? or have I missed some other cause that will make me feel dumb?
thisinside ajQuery.eachwill have a different scope. You need to save it first in a local variable:Note that you example
.setCSS("border","5px solid green");will not work using this method, as it requires the argument to be an object using key/values.However, you should be able to simplify the method to:
That way you can use it the same way jQuery uses
.css()including your implementation example.Fiddles:
First example: http://jsfiddle.net/ESrSY
Second example: http://jsfiddle.net/UpEPK