我想根据元素的标题/描述对列表进行排序。
根据第一个单词,分配权重以稍后定义自定义顺序。
发件人:
收件人:
我们不控制的任何标题将被分配一个 预定的重量(最重),使其出现在末端。
var list = $('.list');
var listItems = list.children('li').get();
$(listItems).each(function() {
var $this = $(this);
var description, focusDescription;
var weight;
description = $this.find('span.description a').text();
focusDescription = description.split(' ')[0];
switch (focusDescription) {
case 'First':
weight = 1;
// code block logic
break;
case 'Second':
weight = 2;
// code block logic
break;
case 'Third':
weight = 3;
// code block logic
break;
case 'Fourth':
weight = 4;
// code block logic
break;
default:
weight = 5;
// code block logic
}
});
listItems.sort(function(a, b) {
// code block logic
})
$.each(listItems, function(idx, itm) {
list.append(itm);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list">
<li class="list-element">
<span class="description">
<a href="#">Third element in list</a>
</span>
<span class="years">4</span>
<span class="EC">200</span>
</li>
<li class="list-element">
<span class="description">
<a href="#">First element in list</a>
</span>
<span class="years">3</span>
<span class="EC">200</span>
</li>
<li class="list-element">
<span class="description">
<a href="#">First element in list</a>
</span>
<span class="years">3</span>
<span class="EC">200</span>
</li>
<li class="list-element">
<span class="description">
<a href="#">Fourth element in list</a>
</span>
<span class="years">5</span>
<span class="EC">200</span>
</li>
<li class="list-element">
<span class="description">
<a href="#">Second element in list</a>
</span>
<span class="years">2</span>
<span class="EC">200</span>
</li>
<li class="list-element">
<span class="description">
<a href="#">Second element in list</a>
</span>
<span class="years">2</span>
<span class="EC">200</span>
</li>
</ul>
答案 0 :(得分:1)
您可以通过定义一个JS对象来对它们进行排序,并优先考虑每个单词。因此,您将使用此优先级作为排序功能的等级。您的js代码如下所示:
var rank = {
First:0,
Second:1,
Third:2,
Fourth:3,
}
var list = $('.list');
var listItems = list.children('li').get();
listItems.sort(function(a, b) {
return rank[$(a).find('span.description a').text().split(' ')[0]] - rank[$(b).find('span.description a').text().split(' ')[0]]
})
$.each(listItems, function(idx, itm) {
list.append(itm);
});