使用jquery基于索引对div进行排序

时间:2016-11-12 21:48:55

标签: jquery html

我根据他们当前所处的位置对3个div进行排序。排序工作正常,但我很难获得每个div的索引值。

问题是,

  • 当我点击(向下箭头)div 2时,它给出了索引值0,它应该给我1。
  • 如果我点击div 3(向上箭头),它会给出 我0而不是2

Html代码:

<div class="flow-container">
  <div class="flow-block">
    <div class="sort-arrows">
      <span class="fa fa-arrow-up" id="sort-up"></span>
      <span class="fa fa-arrow-down" id="sort-down"></span>
    </div>
    <div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
      <h3 class="bg-primary">Div 1</h3>
    </div>
  </div>
  <div class="flow-block">
    <div class="sort-arrows">
      <span class="fa fa-arrow-up" id="sort-up"></span>
      <span class="fa fa-arrow-down" id="sort-down"></span>
    </div>
    <div class="flow-content" data-key="q2qlvpm98n7d2kejzx3g5jy41r6wzx0p">
      <h3 class="bg-primary">Div 2</h3>
    </div>
  </div>
  <div class="flow-block">
    <div class="sort-arrows">
      <span class="fa fa-arrow-up" id="sort-up"></span>
      <span class="fa fa-arrow-down" id="sort-down"></span>
    </div>
    <div class="flow-content" data-key="q2qlvpm98n7d2kejzx3g5jy41r6wzx0p">
      <h3 class="bg-primary">Div 3</h3>
    </div>
  </div>
</div>

演示 - https://jsfiddle.net/gvyoj63a/2/

任何帮助,如果高度赞赏。

3 个答案:

答案 0 :(得分:2)

更改

var pos = $(this).parent().index();

var pos = $(this).closest('.flow-block').index();

as .p​​arent()选择包含向上和向下箭头的div。

答案 1 :(得分:1)

Your selector for getting the index is selecting the div group that's wrapping the arrows, not the item div.

try something like:

var pos = $(this).parent().parent().index();

答案 2 :(得分:0)

清洁代码

$("body").on('click tap', '.fa-arrow-down, .fa-arrow-up', function(e) {
  e.preventDefault();
  var elem = $(this).closest(".flow-block");
  var pos = elem.index();
  alert(pos);
  if($(this).hasClass('fa-arrow-down')) {
    elem.next().after(elem);
  } else {
    elem.prev().before(elem);
  }
});