I create windows like this:
var obj = document.createElement('div');
obj.className = 'window';
obj.style.width = 300 + 'px';
obj.style.height = 200 + 'px';
obj.style.left = 30 + 'px';
obj.style.top = 200 + 'px';
//and so on
and what I need is to attach some data to each window. The data will be grabbed via Ajax and displayed in the windows. How should I do it so that each window hold its own unique data?
I don't need to display the whole data every time and this data would need be organized before being displayed, so I can't just add it with innerHTML. I need a way to hold it somewhere else where I could easily get it and then display it with innerHTML.
-
1Welcome to SO, please visit stackoverflow.com/faqReigel Gallarde– Reigel Gallarde2010年06月10日 04:34:39 +00:00Commented Jun 10, 2010 at 4:34
-
This question is similar to: How can I attach "meta data" to a DOM node?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2024年08月01日 08:56:39 +00:00Commented Aug 1, 2024 at 8:56
4 Answers 4
Could you use jQuery? jQuery has something called data so in your example you could do:
var obj = $('<div></div>');
obj.addClass('window');
obj.data('foo', 'setting some data here');
you can access your data later on with:
obj.data('foo') // will return 'setting some data here'
Comments
Just use
obj.data = yourData;
to get the data use obj.data
1 Comment
A wild guess -
obj.data = 'Whatever'
And later
obj.innerHTML = format(obj.data);
I tried this in my Firebug console, worked there. Maybe worth trying in others?
Comments
You could build your own constructor function to create your own window objects and store the DOM element and the data on each instance, e.g.:
function MyWindow (width, height /*, ...*/) {
var data = {}; // here the data will be stored
// the DOM element
this.element = document.createElement('div');
this.element.className = 'window';
//...
// a method for get and set key/value pairs:
this.data = function (key, value) {
if (typeof value == 'undefined') {
return data[key];
} else {
data[key] = value;
return this;
}
};
}
MyWindow.prototype.sharedMethod = function () {
// shared across all instances, you can access here public members
// like the `this.data` method and the `this.element` DOM element
};
Example usage:
var win1 = new MyWindow(300, 200);
win1.data('key1', 'value1').data('key2', 'value2'); // chainable method :)
// to access the DOM element:
win1.element;
// to get the values
win1.data('key1'); // "value1"
win1.data('key2'); // "value2"
var win2 = new MyWindow(300, 200);
win2.data('someData', {foo: 'bar', baz: true});
win2.data('someData').foo; // "bar"