【问题标题】:How can I shuffle only the first column of a table? [closed]我怎样才能只打乱表格的第一列? [关闭]
【发布时间】:2012-09-04 06:40:43
【问题描述】:

我正在使用来自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)

但这与我想要的相反——它打乱了所有行第一列。我怎样才能改变它,让它洗牌第一列?

【问题讨论】:

    标签: jquery shuffle


    【解决方案1】:

    这是我想出的:

    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",它将随机排序 rows。

    更新:

    “我不明白 [] 做了什么?”

    JavaScript 数组有一个.sort() method,它允许你传入一个自定义的排序比较函数,就像我上面使用的那样,它返回一个介于 -0.5 和 +0.5 之间的随机数,以随机排序。但是 jQuery 对象不是数组,所以你不能只在 $copies jQuery 对象上说 $copies.sort(...)。但是,jQuery 对象是 like 数组,因为它们具有数字索引元素和 length 属性,如果您使用.call().apply() 方法来调用它们。我可以说:

    Array.prototype.sort.call($copies, ...
    

    ...但是我选择了更容易输入的:

    [].sort.call($copies, ...
    

    ...其中[] 只是一个空数组,仅用于提供对数组.sort() 方法的访问。排序将应用于作为.call 的第一个参数的对象,而不是空数组。

    【讨论】:

    • 谢谢!顺便说一句,我无法理解 [] 的作用?
    • 答案已更新,并简要说明了为什么 [].sort.call($copies,...)$copies jQuery 对象进行排序。 (另外,很抱歉,如果您想要的答案是您链接到的代码的修改版本,但是该代码对于应该是一个相当简单的操作来说似乎太长太复杂,所以我忽略了它。)
    猜你喜欢
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多