2012-02-29 46 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