问题
I got a table with three columns:
1 A A
2 B B
3 C C
4 D D
What I want to do is to shuffle the table rows but only the second and third column, like the example below
1 C C
2 A A
3 D D
4 B B
I found a nifty plugin wich lets the table rows to be shuffled
http://www.yelotofu.com/2008/08/jquery-shuffle-plugin/
but I want to keep the first column in it's default order.
Either I will reorder the first column after shuffling or I just shuffle
the second and third column. Either way can somebody help me out with this?
回答1:
Fiddle: http://jsfiddle.net/tGY3g/
Here you go:
(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)
Usage
$("table").shuffleRows()
回答2:
To make sure only the specific table tbody is shuffled, use an ID to identify the affected table, in your JS:
/* Shuffle the table row, identify by id ---- */
$('#shuffle').shuffleRows();
In your HTML, use these:
<table id="shuffle">
<thead>...</thead>
<tbody>
<tr>....</tr>
<tr>....</tr>
<tr>....</tr>
</tbody>
</table>
so that only row in thead is shuffled.
来源:https://stackoverflow.com/questions/7620677/jquery-shuffle-table-rows