如何使用数组索引对无序列表进行排序

时间:2016-03-25 05:32:21

标签: jquery arrays sorting custom-data-attribute

我尝试使用数据属性重新排序列表,请参阅下面的代码。

<ul>
<li data-block="block1">Some Text...</li>
<li data-block="block2">Some Text...</li>
<li data-block="block3">Some Text...</li>
<li data-block="block4">Some Text...</li>
</ul>

在我的jQuery数组中,我有以下值

values = array("block2","block1","block4","block3");

所以我需要按照下面的数组索引的方式对列表进行排序/重新排序。

<ul>
<li data-block="block2">Some Text...</li>
<li data-block="block1">Some Text...</li>
<li data-block="block4">Some Text...</li>
<li data-block="block3">Some Text...</li>
</ul>

请帮助我找到合适的解决方案。

2 个答案:

答案 0 :(得分:3)

您可以使用 sort() 对元素进行排序

&#13;
&#13;
var values = ["block2", "block1", "block4", "block3"];

// get all li with data attribute
var $li = $('li[data-block]');
// sort them based on the index
$li.sort(function(a, b) {
  return values.indexOf($(a).data('block')) - values.indexOf($(b).data('block'));
})
// update the order by appending back to it's parent
.appendTo($li.parent());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li data-block="block1">Some Text...1</li>
  <li data-block="block2">Some Text...2</li>
  <li data-block="block3">Some Text...3</li>
  <li data-block="block4">Some Text...4</li>
</ul>
&#13;
&#13;
&#13;

ES6箭头方法

&#13;
&#13;
var values = ["block2", "block1", "block4", "block3"];

var $li = $('li[data-block]');
$li.sort((a, b) => values.indexOf($(a).data('block')) - values.indexOf($(b).data('block')))
  .appendTo($li.parent());
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li data-block="block1">Some Text...1</li>
  <li data-block="block2">Some Text...2</li>
  <li data-block="block3">Some Text...3</li>
  <li data-block="block4">Some Text...4</li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用.html().map()Attribute Equals Selector [name="value"]

&#13;
&#13;
var values = Array("block2","block1","block4","block3");
$("ul").html(values.map(function(val) {return $("[data-block="+val+"]")}))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul>
  <li data-block="block1">Some Text...1</li>
  <li data-block="block2">Some Text...2</li>
  <li data-block="block3">Some Text...3</li>
  <li data-block="block4">Some Text...4</li>
</ul>
&#13;
&#13;
&#13;