Home  >  Article  >  Web Front-end  >  How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?

How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 08:15:30811browse

How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?

Modifying Table Creation Function for a Specific Layout

Given a JavaScript function designed to create a table with 3 rows and 2 cells, this question seeks guidance on how to modify it to replicate a given table layout where there are 3 rows, but only 2 cells in the first and third rows, while the second row has only one cell that spans two rows.

Adapting the JavaScript Code:

The existing function can be adapted using a more succinct approach with the insertRow and insertCell methods, as shown below:

<code class="js">function tableCreate() {
  const body = document.body,
        tbl = document.createElement('table');
  tbl.style.width = '100px';
  tbl.style.border = '1px solid black';

  for (let i = 0; i < 3; i++) {
    const tr = tbl.insertRow();
    for (let j = 0; j < 2; j++) {
      if (i === 2 && j === 1) {
        break;
      } else {
        const td = tr.insertCell();
        td.appendChild(document.createTextNode(`Cell I${i}/J${j}`));
        td.style.border = '1px solid black';
        if (i === 1 && j === 1) {
          td.setAttribute('rowSpan', '2');
        }
      }
    }
  }
  body.appendChild(tbl);
}</code>

This code:

  • Creates a table with a width of 100 pixels and a black border.
  • Loops through 3 rows, creating a new row each time.
  • For each row, it loops through 2 columns, creating a new cell for each column.
  • Adjusts the second row to span two rows by setting the rowSpan attribute to 2.
  • Inspects the row and cell indices to break out of the second loop for the desired layout.

Final Result:

Executing the modified tableCreate function will generate a table with the given layout:

Cell I0/J0 Cell I0/J1
Cell I1/J0 Cell I1/J1
Cell I2/J0

The above is the detailed content of How to Modify a Table Creation Function to Achieve a Specific Layout with Varying Row and Cell Counts in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn