jQuery shuffle表行

net*_*ase 1 jquery shuffle tabular

我有一个有三列的表:

1 AA
2 BB
3 CC
4 DD

我想要做的是洗牌表行,但只有第二和第三列,如下例所示

1 CC
2 AA
3 DD
4 BB

我发现了一个漂亮的插件,可以让桌子行被洗牌
http://www.yelotofu.com/2008/08/jquery-shuffle-plugin/

但我想保留第一列的默认顺序.我要么在洗牌后重新排序第一列,要么只是改组第二和第三列.无论哪种方式都可以帮助我解决这个问题?

Rob*_*b W 5

小提琴:http://jsfiddle.net/tGY3g/

干得好:

(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)
Run Code Online (Sandbox Code Playgroud)

用法

$("table").shuffleRows()
Run Code Online (Sandbox Code Playgroud)