使用此代码我试图随机化我的响应网格,这是一个5x3矩阵。我最终因为附加给孩子而出错,但我编辑了我的代码。基本上,我想要的最终结果是
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
到
10 11 12
13 14 15
7 8 9
1 2 3
4 5 6
格式网格是:
<div id="shuffle">
<div class="text-center">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div></div>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div></div>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div></div>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div></div>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4"></div>
<div class="col-sm-4"></div></div>
'正在使用的jQuery:
function shuffle(tbl) {
var arr = tbl.find("div");
console.log("Finding the arr Value " + arr + " !");
for(
var j, x, i = arr.length; i;
j = parseInt(Math.random() * i),
x = arr[--i], arr[i] = arr[j], arr[j] = x
);
var tmp;
var rows = tbl.find(".col-sm-4").length
console.log("finding the row value " + rows + " !");
//var cols = tbl.find(".col-sm-4:first .row").length
var cols = 3;
console.log("finding the cols value " + cols + " !");
for (i = 0; i < rows; i++){
tmp = tbl.find("col-sm-4").eq(i);
console.log("finding the tmp value " + tmp + " ! ");
tmp.html()
for (j = 0; j < cols; j++)
tmp.append(arr[i*cols+j]);
}
}
jQuery( document ).ready(function() {
shuffle(jQuery("#shuffle"));
});
控制台日志输出
Finding the arr Value [object Object] !
xxx/:923 finding the row value 15 !
xxx/:927 finding the cols value 3 !
xxx/:932 finding the tmp value [object Object] !
答案 0 :(得分:0)
你只是在这里玩杂耍。您可以使用这种方式而不是您编写的那种混乱的jQuery函数来实现:
// get every row in a variable
//[Note: Use other class if you have other rows than these]
var rowX = $('.row:nth-child(x)'); //here, x = 1 to 5
// remove the parent node html
$('.text-center').html('');
// append the rows one by one in whatever order you need
$('.text-center').append(rowX); //x = 1 to 5
答案 1 :(得分:0)
这是一个相当短的版本。它会自行计算第一行中每行的项目数。
改组后,使用slice()
每行创建新的项目集合
// array shuffle utility
function shuffle(o) {
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
function shuffleRows($rows) {
var $items = $rows.children(),
num_cols = $rows.eq(0).children().length,
numRows = $rows.length;
shuffle($items);
for (var i = 0, j = 0; i < $items.length; i += num_cols, j++) {
$rows.eq(j).append($items.slice(i, i + num_cols + 1))
}
}
shuffleRows($('#shuffle .row'))
的 DEMO 强>