我根据他们当前所处的位置对3个div进行排序。排序工作正常,但我很难获得每个div的索引值。
问题是,
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/
任何帮助,如果高度赞赏。
答案 0 :(得分:2)
更改
var pos = $(this).parent().index();
到
var pos = $(this).closest('.flow-block').index();
as .parent()选择包含向上和向下箭头的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);
}
});