2014-05-20 89 views
2

我有這個功能單列轉換爲多列

function renderListSelecoes(data) { 
    // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one') 
    var list = data == null ? [] : (data.selecoes instanceof Array ? data.selecoes : [data.selecoes]); 

    $('#selecaoList <tr><td>').remove(); 
    $.each(list, function(index, selecao) { 
     $('#selecaoList').append('<tr><td><a href="#" data-identity="' + selecao.id_selecao + '">'+selecao.nome+'</a></td></tr>'); 
    }); 
} 

that's插入每一行表中的東西,像這樣:

Brasil 
Argentina 
Colômbia 
Uruguai 
Suíça 
Argélia 
Costa do Marfim 
Gana 

我怎樣才能將它轉換爲例如2columns,像這樣:

Brasil   Costa do Marfim 
Argentina  Gana 
Colômbia  Argélia 
Uruguai  Suiça 

這裏是HTML我的代碼部分:

<div class="table-responsive container" > 
     <table class="table"> 
      <tbody id="selecaoList"> 

      </tbody> 
     </table> 
    </div> 
+0

是數據在陣列?到第2列和第1列是否有關係? – PeterKA

+0

它可以是別的東西比表嗎?如果您可以使用未排序的列表而不是表格,則可以使用CSS。見http://csswizardry.com/demos/multiple-column-lists/ –

回答

2

這裏是你如何能做到這一點:

function renderListSelecoes(data) { 
    // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one') 
    var list = data == null ? [] : (data.selecoes instanceof Array ? data.selecoes : [data.selecoes]); 

    $('#selecaoList').empty(); 
    var tr = $('<tr/>'), 
     td = $('<td/>'), 
     row; 
    $.each(list, function(index, selecao) { 
     if(index % 2 === 0) { 
      row = tr.clone(); 
      row.html(td.clone().html(selecao.nome)); 
     } else { 
      row.append(td.clone().html(selecao.nome)); 
      $('#selecaoList').append(row); 
     } 
    }); 
} 
+0

謝謝你的幫助,它的工作正常,只需將selecao更改爲selecao.nome ... – seal

+0

太棒了!很高興爲你工作。完成。 – PeterKA

0

你可以做類似如下:

var list=["Brasil","Argentina","Colômbia","Uruguai","Suíça","Argélia","Costa do Marfim", "Gana"]; 
if(list.length %2 ==1){ 
    list.push("");/* pad array if not even number*/ 
} 
var middle= list.length/2; 
var html='' 
for(i=0; i < middle; i++){  
    html+='<tr><td>'+list[i]+'</td><td>'+list[middle+i] + '</td></tr>'; 
} 
$('table').html(html) 

DEMO