2016-01-28 45 views
0

使用此代碼我試圖隨機化我的響應式網格,這是一個5x3矩陣。我最終得到錯誤追加到一個孩子,但我編輯了我的代碼。基本上,最終的結果,我想是這樣如何洗牌/隨機化引導響應網格?

1 2 3 
4 5 6 
7 8 9 
10 11 12 
13 14 15 

10 11 12 
13 14 15 
7 8 9 
1 2 3 
4 5 6 

格式化網格:

<div id="shuffle"> 
<div class="text-center"> 
    <div class="row"> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div></div> 
    <div class="row"> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div></div> 
    <div class="row"> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div></div> 
    <div class="row"> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div></div> 
    <div class="row"> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div> 
     <div class="col-sm-4"></div></div> 

「正在使用的的jQuery:

function shuffle(tbl) { 
    var arr = tbl.find("div"); 

    console.log("Finding the arr Value " + arr + " !"); 
    for(
     var j, x, i = arr.length; i; 
     j = parseInt(Math.random() * i), 
     x = arr[--i], arr[i] = arr[j], arr[j] = x 
    ); 

    var tmp; 
    var rows = tbl.find(".col-sm-4").length 
    console.log("finding the row value " + rows + " !"); 

    //var cols = tbl.find(".col-sm-4:first .row").length 
    var cols = 3; 
    console.log("finding the cols value " + cols + " !"); 


    for (i = 0; i < rows; i++){ 
     tmp = tbl.find("col-sm-4").eq(i); 
    console.log("finding the tmp value " + tmp + " ! "); 
     tmp.html() 
     for (j = 0; j < cols; j++) 

     tmp.append(arr[i*cols+j]); 

    }  
} 

jQuery(document).ready(function() { 
    shuffle(jQuery("#shuffle")); 
}); 

'

控制檯日誌輸出

Finding the arr Value [object Object] ! 
xxx/:923 finding the row value 15 ! 
xxx/:927 finding the cols value 3 ! 
xxx/:932 finding the tmp value [object Object] ! 

回答

0

這是一個相當短的版本。它自行計算第一行每行的項目數量。

洗牌後使用slice()到每行

// array shuffle utility 
function shuffle(o) { 
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); 
    return o; 
} 


function shuffleRows($rows) { 

    var $items = $rows.children(), 
    num_cols = $rows.eq(0).children().length, 
    numRows = $rows.length; 

    shuffle($items); 

    for (var i = 0, j = 0; i < $items.length; i += num_cols, j++) { 
    $rows.eq(j).append($items.slice(i, i + num_cols + 1)) 
    } 

} 

shuffleRows($('#shuffle .row')) 

DEMO

創建新項目集合
0

你只是在這裏玩雜耍行。你可以用這種方式做到這一點,而不是你寫的那種凌亂的jQuery函數:

// get every row in a variable 
//[Note: Use other class if you have other rows than these] 
var rowX = $('.row:nth-child(x)'); //here, x = 1 to 5 

// remove the parent node html 
$('.text-center').html(''); 

// append the rows one by one in whatever order you need 
$('.text-center').append(rowX); //x = 1 to 5