[英]How to change the order of elements in a matched jQuery set
我正在寫一個基於JavaScript的過濾器:
有很多.single
類的div,其中包含多個文本元素。 過濾器已經隱藏了所有不包含單詞的.single
:
//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
的所有索引,其中至少包含一個單詞。 數組templates
包含對象,每個對象帶有.single
文本,以及基於相關性和單詞數的分數。 例如:
templates = [
{ text: ['long string', 'long string 2'], score: 5 },
{ text: ['sf sd', 'gdasd'], score: 3 }
]
(因此所有索引都不會在DOM中發生)
現在,我想要的是根據該分數對集合進行排序,或者換句話說:最高分數。 集合中每個元素的索引與templates
(包含所有分數)中的索引相同。
如果將分數作為元素添加為$ .each中的data()
$(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
索引順序進行操作,但是它們必須已經按照該順序排列,以便您可以使用$ .each中的index查看templates
中的分數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.