I'm not an expert with JavaScript!
I have a simple array/object that I need to add to a JavaScript table. 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. The width of 1-6 will change as well.
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.