2012-02-29 84 views
0

我写一个基于JavaScript的过滤器:如何更改匹配的jQuery元素的顺序设置

一个大量的div有与包含多个文本元素的类.single。该过滤器已经隐藏了所有.single“不包含单词S:

//take them off dom, manip and put them back 
singles.detach().each(function(i) { 
    var $this = $(this); 

    //make sure everything is visible 
    $this.show(); 

    //if this template is not included OR if this index number does not meet the treshold 
    if($.inArray(i, included) == -1 || treshold >= templates[i].score) { 
     $this.hide(); 
    } 
}).appendTo(container); 

数组included包含.single所有索引”是至少含有一个一个字S。数组templates包含每个.single包含所有文本的对象以及基于相关性和单词数量的分数。例如:

templates = [ 
    { text: ['long string', 'long string 2'], score: 5 }, 
    { text: ['sf sd', 'gdasd'], score: 3 } 
] 

(因此,所有的索引不会在DOM发生)

现在,我要的是在此基础上的分数,或者换句话说集合进行排序:上得分最高最佳。该集合中的每个元素的索引与templates(其中包含所有分数)中的索引相同。

回答

1

如果比分添加到元素数据()在$。每个

$(this).data('score', templates[i].score); 

然后,您可以用分数来排序

function scoreSort(a, b) { 
    return $(a).data('score') > $(b).data('score') ?1 :-1; 

} 

singles.sort(scoreSort); 

/* now replace html*/ 

container.append(singles); 

我可能失去了一些东西,你说你希望它们的索引顺序为templates,但它们必须已经按照该顺序让你看看templates中的分数,使用索引在$。每个

+0

我使用$(elem).each()而不是$ .each ()。模板和集合已经在相同的顺序,所以我可以使用'data'绑定分数(感谢提示)。然而,你建议的排序并不按比分排序,而是显示不同的结果(我不明白为什么)。 – askmike 2012-02-29 16:12:49

+0

我尝试了一个简单的演示http://jsfiddle.net/bKfwv/ – charlietfl 2012-02-29 16:16:21

+0

你是对的,它的工作原理。那必须是我的其他代码。感谢您的解决方案! – askmike 2012-02-29 16:18:32