【发布时间】:2010-10-04 19:37:28
【问题描述】:
我想将元素作为键存储在我的数组中,将对象存储为值,例如 -
var arr = [];
arr[ document.getElementById('something') ] = { data: 'something' , fn : function(){ } };
但问题是:如果我要添加另一个元素,其键为:document.getElementById('otherthing')。
稍后会尝试获取:arr[ document.getElementById('something') ].data 的值,我将获取arr[ document.getElementById('otherthing') ] 的值。
例如:
var arr = [];
arr[ document.getElementById('something') ] = { data: 'something' , fn : function(){ } };
arr[ document.getElementById('otherthing') ] = { data: 'otherthing' , fn : function(){ alert('k'); } };
alert( arr[ document.getElementById('otherthing') ].data ); // alerts "otherthing"
alert( arr[ document.getElementById('something') ].data ); // alerts "otherthing" but suppose to alert "something"
我该如何解决这个问题,我无法通过 id 保存,因为我想支持其他没有 id 的节点
谢谢,Yosy。
编辑:我对此的回答,如果您有更好的答案,请写出来 :)(灵感来自 casablanca 的回答)
id 数组:key-integer 节点 id,值节点自身
以及带有数据的数组和带有我的 id 键的 fn,它看起来像这样:
var idArray = [],nodeArray = [];
idArray[0] = document.getElementById('hello_ducks');
nodeArray[0] = { data: 'hello ducks!!' , fn : function(){ alert('k'); } };
idArray[1] = document.getElementById('hello');
nodeArray[1] = { data: 'hello' , fn : function(){ } };
var testNode = document.getElementById('hello_ducks'), foundId = -1 /*found id*/;
// Do we have testNode in our array?
for(var i = 0 ; i < idArray.length; i++ ){
if( idArray[i] === testNode ){
foundId = i;
}
}
// Do we found our element?
if(foundId >= 0) {
alert( nodeArray[foundId].data ); // "hello ducks!!"
}
【问题讨论】:
-
如果你想使用 jQuery,有一个
.data方法,这可能就是你想要的。 api.jquery.com/data -
查看我的更新答案以获得更简单的方法。
标签: javascript dom