2014-07-18 70 views
0

我不是JavaScript的專家!如何添加項目到Javascript數據數組/對象

我有一個簡單的數組/對象,我需要添加到JavaScript表。 事情是這樣的:

var columns = { 
       "0": { "styles": "width:22%;" }, 
       "1": { "styles": "width:13%;" }, 
       "2": { "styles": "width:13%;" }, 
       "3": { "styles": "width:13%;" }, 
       "4": { "styles": "width:13%;" }, 
       "5": { "styles": "width:13%;" }, 
       "6": { "styles": "width:13%;" } 
      }; 

然而,「列」變量取決於有多少記錄必須改變...所以0將始終是相同的(22%),但1-5取決於有多少由用戶和6定義的列是「總計」列。 1-6的寬度也會改變。

我知道如何獲得列的數量,但不知道如何創建列的列表,併產生像上面的「列」聲明。

+2

技術上上述結構是一個對象不是一個數組 – vogomatix

回答

1

你可以嘗試這樣的事:

var table = document.getElementById('myTable'), // table to perform search on 
    row = table.getElementsByTagName('tr')[0], 
    columnsCount = row.getElementsByTagName('td').length, 
    columns = {0: { styles: 'width: 22%' }}; 

for (var i = 1; i < columnsCount; i++) { 
    columns[i] = {styles: 'width: ' + Math.floor((100-22)/(columnsCount - 1)) + '%'} 

    row.getElementsByTagName('td')[i].style = columns[i].styles; 
} 

console.log(columns); 

下面是一個工作示例:http://jqversion.com/#!/afxvKvE

1
var columns = [ 
    { "styles": "width:22%;" }, 
    { "styles": "width:13%;" }, 
    { "styles": "width:13%;" }, 
    { "styles": "width:13%;" }, 
    { "styles": "width:13%;" }, 
    { "styles": "width:13%;" }, 
    { "styles": "width:13%;" } 
    ]; 

// add a elements to array 
for (i = 0; i < 10; i++) { 
    var width = '12'; // whatever width you want for each element. 
    columns.push('{ "styles": "width:' + width + '%;" }'); 
} 
+0

怎樣包括0 - 6「 1「:{」styles「:」width:13%「} – Rob

+0

它們是隱含的 - 元素0..6在 – vogomatix

+1

以上的初始化程序中我認爲你誤用了你的引號:它是columns.push({」styles「 :「width:」+ width +「%;」});' – dgiugg

相關問題