简体   繁体   中英

How can I split table rows into 2 equal columns with JavaScript?

I have a script that will create some links inside table rows and display them.

$('#links').val('<class="sws_gen_links_table">' + links.join('\n'));

$('#linksContainer').show();

What I would like to do before these are displayed is to split them into equal 2 columns and add them into the respective td. Something like this:

<table id="stylewithcss">
<tbody>

<tr>
<td class="This is the header of the table" colspan="2">ADD HEADER HERE</td>
</tr>
<tr>

<td>
Here goes the first part of the links.
</td>

<td>
Here goes the second part of the links.
</td>

</tr>
</tbody>
</table>

I found something similar here but to be honest I don't really know how to apply it in my case (I am a beginner). convert single column to multiple columns

The simplest solution is to split it into 2 arrays (something like this):

for alternating:

const links = ["link one", "link two", "link three", "link four", "link five", "link six", "link seven", "link eight", "link nine"]

const linksOne = []
const linksTwo = []

for (let i = 0; i < links.length; i++) {
  const link = links[i]
  if (i % 2 === 0) linksOne.push(link)
  else linksTwo.push(link)
}

for not alternating:

const links = ["link one", "link two", "link three", "link four", "link five", "link six", "link seven", "link eight", "link nine"]
const mid = Math.ceil(links.length / 2)

const linksOne = links.slice(0, mid)
const linksTwo = links.slice(mid)

You can try storing the links into an array, then divide the length of the array by 2 and display the first half in the first column and the second half in the second column. If the length is odd then push an empty string into the array to make it even. for example,

 var links=["link1","link2","link3","link4"]; if(links.length % 2 == 1){ links.push(""); } var midpoint= links.length/2; var html='<tr><td class="" colspan="2">ADD HEADER HERE</td></tr>' for(i=0; i<midpoint; i++){ html+='<tr><td>'+links[i]+'</td><td>'+links[midpoint+i] + '</td></tr>'; } document.getElementById('stylewithcss').innerHTML = html;
 <table id="stylewithcss"> </table>

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.

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