jQuery随机排序表行 [英] jQuery shuffle table rows

查看:168
本文介绍了jQuery随机排序表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三列的表:

I got a table with three columns:

1 A A
2 B B
3 C C
4 D D

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

1 C C
2 A A
3 D D
4 B B

我发现了一个漂亮的插件,它可以让表行被重新排列
http://www.yelotofu.com/2008/08/jquery-shuffle -plugin/

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?

推荐答案

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

Fiddle: 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)

用法

$("table").shuffleRows()

这篇关于jQuery随机排序表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆