jQuery是否具有哈希表类型的可变数据结构?

时间:2011-05-03 16:41:27

标签: jquery data-structures

伪代码可能是展示我在jQuery中要做的事情的最佳方式:

$(selector).each(function() {
    // pull data from LI tags or whatever, store in variables (imgURL, tagline, summary)
    $someDataStructure.add({imgURL, tagline, summary});
});

然后......引用结构

 $someDataStructure.each(function() {
     var x = $someDataStructure['imgURL'];
     // etc.
 });

关于如何做到这一点的任何建议?

2 个答案:

答案 0 :(得分:8)

jQuery只是JavaScript,JavaScript有对象。您可以像使用C ++映射或C#字典一样使用JS对象。例如,您可以创建一个对象数组,并具有可以命名的索引:

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

然后:

for(int i = 0; i < liTags.length; ++i) {
   var imgURL = liTags[i]['imgURL']; //or liTags[i].imgURL;
}

答案 1 :(得分:1)

您实际上可以使用data api

将数据附加到jquery元素

所以做一些事情:

$(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 */
}

然后从每个jquery元素中检索它!

$(selector).data()

$(selector).data('imgURL')

用于将'哈希表'附加到元素。

在javascript中你有'associative arrays'(哈希表)。

你可以把它们写成: myarray = {key:'value'}

您可以按以下方式访问它们:

根据您的喜好

myarray['attribute']myarray.attribute

PS。请注意,我没有在那里测试代码,可能需要一些小的调整