Pseudo-code is probably the best way to show what I'm looking to do in jQuery:
$(selector).each(function() {
// pull data from LI tags or whatever, store in variables (imgURL, tagline, summary)
$someDataStructure.add({imgURL, tagline, summary});
});
Then later... reference the structure
$someDataStructure.each(function() {
var x = $someDataStructure['imgURL'];
// etc.
});
Any suggestions on how I could go about doing this?
jQuery is just JavaScript, and JavaScript has objects. You can use JS Objects similarly to a C++ map or C# Dictionary. For example, you can create an array of objects and have indices that you can name:
var liTags = [];
$(selector).each(function() {
// pull data from LI tags or whatever
//store in variables (imgURL, tagline, summary)
liTags.push({'imgURL': imgURL, 'tagline': tagline, 'summary': summary});
});
Then later:
for(int i = 0; i < liTags.length; ++i) {
var imgURL = liTags[i]['imgURL']; //or liTags[i].imgURL;
}
You can actually attach data to a jquery element using the data api
So do something in the lines of:
$(selector).each(function() {
/* I suppose here you have three available variables named:
imgURL, tagline, summary
that you got from the element itself or from somewhere else
*/
$(this).data({imgURL: imgURL, tagline: tagline, summary:summary })
/* you could also write it {'imgURL': imgURL, etc. } if it looks clearer: the first is the hashtable key, the second a variable containing the value */
}
and then just retrieve it from each jquery element!
$(selector).data()
or
$(selector).data('imgURL')
That's for attaching an 'hashtable' to an element.
In javascript you have 'associative arrays' (hashtables).
You can write them as:
myarray = {key:'value'}
and you can access them as:
myarray['attribute']
or myarray.attribute
as you prefer
PS. please note that I did not test the code up there, it might require some minor tweaks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With