jQuery分组类似项目w / Object Literal

时间:2010-06-15 21:24:51

标签: jquery arrays structure

所以我有这个结构设置:

<ul>
    <li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li> (Vid1)
    <li>http://www.youtube.com/watch?v=bOF3o8B292U</li> (Vid2)
    <li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li> (Vid3)
    <li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li>
    <li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li>
    <li>http://www.youtube.com/watch?v=bOF3o8B292U</li>
    <li>http://www.youtube.com/watch?v=yAY4vNJd7A8</li>
    <li>http://www.youtube.com/watch?v=dw1Vh9Yzryo</li>
</ul>

Vid1重复3次,Vid2重复3次,Vid3重复2次。我想将它们放入一个我可以像这样引用它们的结构中:

youtube [0] [重复] = 3; youtube [0] [download] =“http://www.youtube.com/get_video?video_id=dw1Vh9Yzryo&fmt=36

youtube [1] [重复] = 3; youtube [1] [download] =“http://www.youtube.com/get_video?video_id=bOF3o8B292U&fmt=36

youtube [2] [重复] = 3; youtube [2] [download] =“http://www.youtube.com/get_video?video_id=yAY4vNJd7A8&fmt=36

"This video was repeated " + youtube[0][repeated] + " times and you can download it here: " + youtube[0][download];

如何设置此多维数组?谷歌搜索了几个小时,我不知道如何设置它。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

看看JQuery: Remove duplicate elements?

var seen = {};
$('li').each(function() {
    var txt = $(this).text();
    if (seen[txt])
        seen[txt] += 1;
    else
        seen[txt] = 1;
});

现在seen看起来像

{ "http://www.youtube.com/watch?v=dw1Vh9Yzryo": 3,
  "http://www.youtube.com/watch?v=yAY4vNJd7A8": 2,
  [...]
}

然后,您可以创建一个新列表:

newlist = $('<ul />');
for (var vid in seen) {
    $("<li>This video was repeated " + seen[vid] + " times and you can download it here: " + vid + "</li>").appendTo(newlist);
}
newlist.appendTo(document.body); // or wherever you want it

您可以在http://jsfiddle.net/CqMcY/

上看到此问题

答案 1 :(得分:0)

好的,我已经弄明白了。我需要的结构是通过使用 Object Literal

实现的
var youtube = {};

function makeDLLink(video)
{
    return "*Download Link*";
}

$('li').each(function() {
    var videoLink = $(this).text();
    var download = makeDLLink(videoLink);
    if (!youtube[videoLink])
    {
        youtube[videoLink] = { "repeated": 1, "download": download };
    }
    else
    {
        youtube[videoLink].repeated += 1;
    }
});

$('ul').append("<br /><br /><br />");
for (var key in youtube)
{
    var obj = youtube[key];
    $('ul').append(key + " was repeated " + obj.repeated + " times and can be DL'd from " + obj.download + "<br /><br />");
}

您可以在at jsFiddle.

上看到它