简体   繁体   中英

Javascript add new row with <tr> then remove at the last row

I have simple question regarding table row.

Below is the example:

 var data = ['A', 'B', 'C', 'D', 'E']; for(var i=0; i<data.length; i++) { var element = ` <td>${i}</td><tr> `; console.log(element); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The result from console.log is:

<td>0</td><tr>
<td>1</td><tr>
<td>2</td><tr>
<td>3</td><tr>
<td>4</td><tr>

Now I need at the last row <td>4</td><tr> no need this <tr> . It should be like this <td>4</td> .

Is there any trick to handle it?

You can try this:


for(let i=0; i<data.length; i++) {
  let element = `<td>${i}</td>`;
  if (i !== data.length-1) {
    element += "<tr>";
  }
  console.log(element);
}

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