[英]How to add items to a Javascript data array/object
I'm not an expert with JavaScript! 我不是JavaScript专家!
I have a simple array/object that I need to add to a JavaScript table. 我有一个简单的数组/对象,需要将其添加到JavaScript表中。 Something like this:
像这样:
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%;" }
};
However the "columns" variable has to change depending on how many records I have... so 0 will always be the same (22%) but 1-5 depends on how many columns defined by user and 6 is a "total" column. 但是,“ columns”变量必须根据我拥有的记录数进行更改...因此,0始终是相同的(22%),但是1-5取决于用户定义的列数,而6是“总计”列。 The width of 1-6 will change as well.
1-6的宽度也会改变。
I know how to get the number of columns but just not sure how I create the list of columns and produce something like above "column" declaration. 我知道如何获取列数,但只是不确定如何创建列列表并产生类似于“ 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 + '%;" }' );
}
You may try something like this: 您可以尝试如下操作:
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);
Here is an working example: http://jqversion.com/#!/afxvKvE 这是一个工作示例: http : //jqversion.com/#!/afxvKvE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.