【问题标题】:jQuery shuffle table rowsjQuery shuffle 表行
【发布时间】:2011-10-01 13:56:32
【问题描述】:

我有一个三列的表格:

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

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

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

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

但我想保持第一列的默认顺序。 要么我会在洗牌后重新排序第一列,要么我只是洗牌 第二列和第三列。无论哪种方式,有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: jquery shuffle tabular


    【解决方案1】:

    小提琴: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()
    

    【讨论】:

    • 听起来棒极了!但我无法让它运行。我叫它 $('tr').shuffleKeepFirst();
    • 已编辑答案。现在,shuffleKeepFirst 函数不仅适用于数组,还适用于类似数组的对象,例如 DOM 节点。
    • 它在第二列和第三列之间随机播放,但不在行内?
    • 应用到表格中,除了第一行之外的所有行都会被排序...你指的是一个没用的插件,我为什么要给你修改?我将创建一个新的 shuffle 函数,尽可能少地使用 JQuery(JQUery + DOM 元素排序 = 性能不佳)。
    • 你的代码在 div 上完美运行,但看看我的桌子:jsfiddle.net/AwYWw
    【解决方案2】:

    为了确保只有特定的表 tbody 被打乱,在你的 JS 中使用一个 ID 来识别受影响的表:

    /* Shuffle the table row, identify by id ---- */
    $('#shuffle').shuffleRows();
    

    在您的 HTML 中,使用这些:

    <table id="shuffle">
     <thead>...</thead>
     <tbody>
      <tr>....</tr>
      <tr>....</tr>
      <tr>....</tr>
     </tbody>
    </table>
    

    这样只有前行被打乱了。

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      相关资源
      最近更新 更多