当前位置:首页 > JavaScript

js实现表格

2026-03-14 23:39:27JavaScript

使用原生JavaScript创建表格

创建表格的基本方法是使用document.createElement动态生成table元素及其子元素(theadtbodytrtd等)。以下是一个完整示例:

// 创建表格元素
const table = document.createElement('table');
table.setAttribute('border', '1');

// 创建表头
const thead = table.createTHead();
const headerRow = thead.insertRow();
const headers = ['Name', 'Age', 'City'];
headers.forEach(text => {
  const th = document.createElement('th');
  th.textContent = text;
  headerRow.appendChild(th);
});

// 创建表格数据
const tbody = table.createTBody();
const data = [
  ['Alice', 24, 'New York'],
  ['Bob', 30, 'London'],
  ['Charlie', 28, 'Sydney']
];
data.forEach(rowData => {
  const row = tbody.insertRow();
  rowData.forEach(cellData => {
    const cell = row.insertCell();
    cell.textContent = cellData;
  });
});

// 将表格添加到DOM
document.body.appendChild(table);

动态表格操作方法

表格创建后,可能需要动态操作行和单元格:

// 添加新行
function addRow(table, rowData) {
  const row = table.insertRow();
  rowData.forEach(cellData => {
    const cell = row.insertCell();
    cell.textContent = cellData;
  });
}

// 删除指定行
function deleteRow(table, rowIndex) {
  table.deleteRow(rowIndex);
}

// 更新单元格内容
function updateCell(rowIndex, cellIndex, newValue) {
  const row = table.rows[rowIndex];
  if (row) {
    const cell = row.cells[cellIndex];
    if (cell) cell.textContent = newValue;
  }
}

表格排序功能实现

通过点击表头实现排序功能:

headers.forEach((header, index) => {
  header.addEventListener('click', () => {
    const rows = Array.from(tbody.rows);
    rows.sort((a, b) => {
      const valA = a.cells[index].textContent;
      const valB = b.cells[index].textContent;
      return isNaN(valA) ? valA.localeCompare(valB) : valA - valB;
    });
    rows.forEach(row => tbody.appendChild(row));
  });
});

使用模板字符串生成表格

对于简单表格,可以使用模板字符串快速生成HTML:

const tableHTML = `
  <table border="1">
    <thead>
      <tr>
        ${headers.map(h => `<th>${h}</th>`).join('')}
      </tr>
    </thead>
    <tbody>
      ${data.map(row => `
        <tr>
          ${row.map(cell => `<td>${cell}</td>`).join('')}
        </tr>
      `).join('')}
    </tbody>
  </table>
`;
document.body.innerHTML = tableHTML;

响应式表格实现

结合事件委托实现高效的事件处理:

table.addEventListener('click', (e) => {
  const cell = e.target.closest('td');
  if (cell) {
    cell.contentEditable = true;
    cell.focus();
  }
});

table.addEventListener('blur', (e) => {
  const cell = e.target.closest('td');
  if (cell && cell.contentEditable) {
    cell.contentEditable = false;
    // 保存修改后的数据
  }
}, true);

表格分页功能

实现客户端分页功能:

js实现表格

const itemsPerPage = 2;
let currentPage = 0;

function displayPage(page) {
  tbody.innerHTML = '';
  const start = page * itemsPerPage;
  const pageData = data.slice(start, start + itemsPerPage);
  pageData.forEach(row => addRow(tbody, row));
}

document.getElementById('next').addEventListener('click', () => {
  if ((currentPage + 1) * itemsPerPage < data.length) {
    currentPage++;
    displayPage(currentPage);
  }
});

document.getElementById('prev').addEventListener('click', () => {
  if (currentPage > 0) {
    currentPage--;
    displayPage(currentPage);
  }
});

标签: 表格js
分享给朋友:

相关文章

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现复制到剪贴板

js实现复制到剪贴板

使用document.execCommand方法(传统方式,已废弃但部分浏览器仍支持) 该方法适用于旧版浏览器,但已被标记为废弃。执行前需确保文本已被选中: function copyToClipb…

vue实现表格复选

vue实现表格复选

实现表格复选的基本思路 在Vue中实现表格复选功能,通常需要结合v-model绑定选中状态,监听复选框变化事件,以及维护一个选中项的数组。以下是具体实现方法: 基础实现步骤 数据准备 定义表格数据和…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

uniapp 表格导入

uniapp 表格导入

uniapp 表格导入的实现方法 使用 uni.chooseFile 选择文件 在 uniapp 中,可以通过 uni.chooseFile API 让用户选择本地文件。该 API 支持多平台,包括…

vue实现导出表格

vue实现导出表格

Vue 实现导出表格的方法 使用 xlsx 库导出 Excel 安装 xlsx 库 npm install xlsx 在 Vue 组件中引入 xlsx import * as XLSX from…