繁体   English   中英

如何将项目添加到Javascript数据数组/对象

[英]How to add items to a Javascript data array/object

我不是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%;" }
            };

但是,“ columns”变量必须根据我拥有的记录数进行更改...因此,0始终是相同的(22%),但是1-5取决于用户定义的列数,而6是“总计”列。 1-6的宽度也会改变。

我知道如何获取列数,但只是不确定如何创建列列表并产生类似于“ column”声明的内容。

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 + '%;" }' );
}

您可以尝试如下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM