我随机输出每个都有数据索引的div的顺序。我正在使用jQuery-ui作为其可排序方法,因此用户可以重新排列div的顺序。我怎样才能这样做,当你按下一个提交按钮时,会调用一个函数来检查每个元素的数据索引是否有序?
DOM结构如下所示:
<div class="sequence_boxes sortable sortable_area ui-sortable">
<div class="box" data-index="0">..</div>
<div class="box" data-index="1">..</div>
<div class="box" data-index="2">..</div>
<div class="box" data-index="3">..</div>
</div>
我的jQuery:
$('.sequencing').append('<div class="sequence_boxes sortable sortable_area"></div>');
$('.sequence_option').each(function (i) {
$('<div class="box"></div>').appendTo($('.sequence_boxes')).append(this);
$(this).attr("data-index", i);
$(this).parent().attr('data-index', i);
});
$('.sequence_boxes').each(function () {
// get current div
var $div_parent = $(this);
// get array of childs in parent div
var $divsArr = $div_parent.children('.box');
// sort array of childs in parent div (#sponsors) randomly
$divsArr.sort(function (a, b) {
// Get a random number between 0 and 10
var temp = parseInt(Math.random() * 10);
// Get 1 or 0, whether temp is odd or even
var isOddOrEven = temp % 2;
// Get +1 or -1, whether temp greater or smaller than 5
var isPosOrNeg = temp > 5 ? 1 : -1;
// Return -1, 0, or +1
return (isOddOrEven * isPosOrNeg);
})
// append child items to parent
.appendTo($div_parent);
});
$('.sortable_area').sortable({
dropOnEmpty: true,
forcePlaceholderSize: true,
forceHelperSize: false,
connectWith: ".sequence_boxes",
scrollSensitivity: 200,
scrollSpeed: 40,
placeholder: "ui-sortable-placeholder",
cursor: "move",
distance: 0.5,
delay: 100,
opacity: 0.6,
tolerance: "pointer",
}).disableSelection();
答案 0 :(得分:2)
解决方案很简单:
var correct_index = 0;
$('.box').each(function(){
var current_index = $(this).data('index');
if(current_index != correct_index) {
alert('Out of order');
return false;
}
correct_index++;
});
This 是一种更加一致的实施方式:
你的案子:
$('.sequence_boxes .box').isOrdered('asc', 'index');
$(selector).isOrdered(order, data, [fail], [success]);
});
来源:
jQuery.fn.extend({
isOrdered: function(orderBy, data, succ, fail){
var correct_index = 0, o = 1, f = false, t = this;
if(orderBy == 'desc') {
correct_index = this.length - 1;
o = -1;
}
this.each(function(){
var current_index = $(this).data('index');
if(current_index != correct_index) {
if(fail) fail.call(t, this);
f = true;
return false;
}
correct_index += o;
});
if(!f && succ) succ.call(this, this);
return this;
}
});