我正在寻找在同一页面上处理js对象实例时已被发现可接受的模式。 (如果有一个帖子已经涵盖了这一点,我们将不胜感激。)
这个问题是参考之一。在实例化对象/特征之后,必须在稍后的某个时刻引用它。
我见过jQuery人使用data()
存储对目标DOM元素上的对象的引用。但是,如果可能的话,我对框架无关的选项很感兴趣。
如果有一种干净,可行的方法来为DOM元素生成唯一ID,则可以实现这一点。唉,我还没找到。
所以我的问题是:通过DOM元素存储对象的引用的最佳方法是什么,以便您可以在以后的任意时间引用它?
希望这是有道理的,而且我不仅仅是漫无目的。 :)
感谢。
答案 0 :(得分:5)
没有什么可以阻止你维护自己的缓存:
var cache = [];
function locate(el) {
// search for the element within our cache.
for (var i=0;i<cache.length;i++) {
if (cache[i].elem === el) {
return cache[i].data;
};
};
// if we get this far, it isn't in the cache: add it and return it.
return cache[cache.push({
elem: el,
data: {}
}) - 1].data;
};
// used to add data to an element and store it in our cache.
function storeData(el, data) {
var store = locate(el);
for (var x in data) {
store[x] = data[x];
};
};
// used to retrieve all data stored about the target element.
function getData(el) {
return locate(el);
};
然后使用如下:
storeData(document.getElementById("foo"), {
something: 4,
else: "bar"
});
var data = getData(document.getElementById("foo"));
alert(data.something); // "4";
答案 1 :(得分:0)
JavaScript中的对象(与传统的OOP语言不同)可以得到增强。这没有错;这就是JavaScript的设计方式:
写:
document.getElementById('foo')。customAttribute = 5;
读:
alert(document.getElementById('foo')。customAttribute);
如果您不想改变原始对象,指向它的唯一方法是使用前面一个答案中指出的字典;但是,您不需要进行线性搜索来查找对象:它可以在对数时间内完成,前提是您每个元素使用一个ID(可能不是HTML ID而是自定义ID)