我正在使用 this question 中的函数使用 jQuery 打乱表的行。我真正想要的是只打乱第一列,其余部分保持不变,如下所示:
a b c d
e f g h
i j
对此:
e b c d
i f g h
a j
Rob W's answer中的函数是:
(function($){ //Shuffle all rows, while keeping the first column //Requires: Shuffle $.fn.shuffleRows = function(){ return this.each(function(){ var main = $(/table/i.test(this.tagName) ? this.tBodies[0] : this); var firstElem = [], counter=0; main.children().each(function(){ firstElem.push(this.firstChild); }); main.shuffle(); main.children().each(function(){ this.insertBefore(firstElem[counter++], this.firstChild); }); }); } /* Shuffle is required */ $.fn.shuffle = function() { return this.each(function(){ var items = $(this).children(); return (items.length) ? $(this).html($.shuffle(items)) : this; }); } $.shuffle = function(arr) { for( var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x ); return arr; } })(jQuery)
但这与我想要的相反 - 它会打乱除第一列之外的所有行。我如何更改它,以便它仅第一列进行洗牌?
最佳答案
这是我想到的:
var $firstCells = $("#tableIdHere tr td:first-child"),
$copies = $firstCells.clone(true);
[].sort.call($copies, function() { return Math.random() - 0.5; });
$copies.each(function(i){
$firstCells.eq(i).replaceWith(this);
});
也就是说,使用 :first-child
selector 选择所有第一个单元格,复制它们,然后对副本进行随机排序。然后循环遍历(现已随机化)副本并用它们替换原始副本。
演示:http://jsfiddle.net/nnnnnn/ceTmL/
附注请注意,如果您只是更改创建 $firstCells
jQuery 对象的选择器,例如,如果您将选择器更改为 "#tableIdHere tr,则此技术将随机对任何表格单元格或元素集合进行排序“
它将随机对行进行排序。
更新:
"I cannot understand what the
[]
does?"
JavaScript 数组有 .sort()
method它允许您传入一个自定义排序比较函数,就像我上面使用的函数一样,它返回 -0.5 和 +0.5 之间的随机数,以便按随机顺序排序。但 jQuery 对象不是数组,因此您不能只对 $copies
jQuery 对象说 $copies.sort(...)
。然而,jQuery 对象像数组,因为它们具有数字索引元素和 length
属性,以及一些数组方法(包括 .sort()
) 如果您使用 .call()
,则可以在类似数组的对象上调用或 .apply()
方法来调用它们。我本可以说:
Array.prototype.sort.call($copies, ...
...但我选择了更容易输入的方式:
[].sort.call($copies, ...
...其中 []
只是一个空数组,仅用于提供对数组 .sort()
方法的访问。排序将应用于 .call
第一个参数的对象,而不是空数组。
关于jquery - 如何只打乱表格的第一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258042/