当前位置:首页 > JavaScript

js实现表

2026-02-02 04:31:12JavaScript

以下是几种常见的 JavaScript 表格实现方法:

动态生成表格

使用 DOM 操作动态创建表格结构:

js实现表

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

// 创建表头
const thead = table.createTHead();
const headerRow = thead.insertRow();
['姓名', '年龄', '城市'].forEach(text => {
  const th = document.createElement('th');
  th.textContent = text;
  headerRow.appendChild(th);
});

// 创建表格内容
const tbody = table.createTBody();
const data = [
  {name: '张三', age: 25, city: '北京'},
  {name: '李四', age: 30, city: '上海'}
];

data.forEach(item => {
  const row = tbody.insertRow();
  Object.values(item).forEach(value => {
    const cell = row.insertCell();
    cell.textContent = value;
  });
});

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

使用模板字符串

通过字符串拼接生成表格 HTML:

const data = [
  {id: 1, product: '手机', price: 3999},
  {id: 2, product: '笔记本', price: 5999}
];

let html = `
  <table border="1">
    <thead>
      <tr>
        <th>ID</th>
        <th>商品</th>
        <th>价格</th>
      </tr>
    </thead>
    <tbody>
      ${data.map(item => `
        <tr>
          <td>${item.id}</td>
          <td>${item.product}</td>
          <td>${item.price}</td>
        </tr>
      `).join('')}
    </tbody>
  </table>
`;

document.body.innerHTML = html;

使用框架(React 示例)

在 React 中创建表格组件:

js实现表

function DataTable({ data }) {
  return (
    <table>
      <thead>
        <tr>
          {Object.keys(data[0]).map(key => (
            <th key={key}>{key}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map((row, i) => (
          <tr key={i}>
            {Object.values(row).map((val, j) => (
              <td key={j}>{val}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// 使用示例
const products = [
  {id: 1, name: '键盘', stock: 50},
  {id: 2, name: '鼠标', stock: 100}
];

ReactDOM.render(
  <DataTable data={products} />,
  document.getElementById('root')
);

表格排序功能

为表格添加点击排序功能:

function sortTable(table, column, asc = true) {
  const tbody = table.tBodies[0];
  const rows = Array.from(tbody.querySelectorAll('tr'));

  rows.sort((a, b) => {
    const aVal = a.cells[column].textContent;
    const bVal = b.cells[column].textContent;
    return asc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
  });

  while (tbody.firstChild) {
    tbody.removeChild(tbody.firstChild);
  }

  tbody.append(...rows);
}

// 使用示例
document.querySelectorAll('th').forEach(th => {
  th.addEventListener('click', () => {
    const table = th.closest('table');
    const headerIndex = Array.from(th.parentNode.children).indexOf(th);
    sortTable(table, headerIndex);
  });
});

响应式表格

使用 CSS 和 JavaScript 实现响应式表格:

function makeTableResponsive(table) {
  const headers = Array.from(table.querySelectorAll('th')).map(th => th.textContent);
  const rows = table.querySelectorAll('tbody tr');

  rows.forEach(row => {
    const cells = row.querySelectorAll('td');
    cells.forEach((cell, i) => {
      cell.setAttribute('data-label', headers[i]);
    });
  });
}

// 调用函数
const tables = document.querySelectorAll('table');
tables.forEach(makeTableResponsive);

这些方法涵盖了从基础到进阶的表格实现方式,可以根据具体需求选择合适的实现方案。

标签: js
分享给朋友:

相关文章

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callback) {…

js实现验证码

js实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数:…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…