2010-06-10 74 views
1

我創建的窗口是這樣的:JavaScript的OOP問題

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 

和我需要的是一些數據附加到每個窗口。數據將通過Ajax抓取並顯示在窗口中。我應該怎麼做才能讓每個窗口保持自己獨特的數據?

我不需要每次都顯示整個數據以及這些數據需要在顯示前組織,所以我不能只是innerHTML添加。我需要一種方法來保存到其他地方,我可以很容易地得到它,然後用innerHTML顯示。

+1

歡迎SO,請訪問http://stackoverflow.com/faq – Reigel 2010-06-10 04:34:39

回答

0

胡亂猜測 -

obj.data = 'Whatever' 

後來

obj.innerHTML = format(obj.data); 

我在Firebug的控制檯嘗試這樣做,在那裏工作。也許值得在別人嘗試?

1

只需使用

obj.data = yourData; 

獲取數據使用obj.data

+3

事情是大小寫敏感的,所以你的意思是 「obj.data」,而不是 「obj.Data」 – Pointy 2010-06-10 04:37:29

+0

@Pointy是的! ,謝謝:d – Fopfong 2010-06-10 05:03:17

+0

+1最直接的方法 – 2011-07-04 16:56:02

1

你可以使用jQuery? jQuery有一種叫data所以在您的例子,你可以這樣做:

var obj = $('<div></div>'); 
obj.addClass('window'); 
obj.data('foo', 'setting some data here'); 

您可以訪問後您的數據:

obj.data('foo') // will return 'setting some data here' 
+0

+1耶! jQuery的一切..;) – Reigel 2010-06-10 04:48:43

0

你可以建立自己的constructor function創建自己窗口對象並在每個實例上存儲DOM元素和數據,例如:

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 
}; 

示例us年齡:

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"