当前位置:首页 > JavaScript

js实现tableview

2026-02-01 22:35:59JavaScript

实现基本的 TableView 结构

使用 HTML 和 JavaScript 创建一个简单的 TableView,需要定义表格的 DOM 结构并通过 JavaScript 动态填充数据。

<div id="tableViewContainer">
  <table id="tableView">
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
const data = [
  { name: 'Alice', age: 25, email: 'alice@example.com' },
  { name: 'Bob', age: 30, email: 'bob@example.com' },
  { name: 'Charlie', age: 35, email: 'charlie@example.com' }
];

function renderTableView(data) {
  const tbody = document.querySelector('#tableView tbody');
  tbody.innerHTML = '';

  data.forEach(item => {
    const row = document.createElement('tr');
    row.innerHTML = `
      <td>${item.name}</td>
      <td>${item.age}</td>
      <td>${item.email}</td>
    `;
    tbody.appendChild(row);
  });
}

renderTableView(data);

添加排序功能

为 TableView 实现点击表头排序的功能,增强用户体验。

js实现tableview

const table = document.getElementById('tableView');
const headers = table.querySelectorAll('th');

headers.forEach((header, index) => {
  header.style.cursor = 'pointer';
  header.addEventListener('click', () => {
    const column = header.textContent.toLowerCase();
    const sortedData = [...data].sort((a, b) => {
      if (a[column] < b[column]) return -1;
      if (a[column] > b[column]) return 1;
      return 0;
    });
    renderTableView(sortedData);
  });
});

实现分页功能

对于大量数据,添加分页功能可以提高性能并改善用户体验。

let currentPage = 1;
const rowsPerPage = 5;

function paginateData(data, page, rowsPerPage) {
  const start = (page - 1) * rowsPerPage;
  const end = start + rowsPerPage;
  return data.slice(start, end);
}

function renderPaginationControls(totalPages) {
  const paginationDiv = document.createElement('div');
  paginationDiv.className = 'pagination';

  for (let i = 1; i <= totalPages; i++) {
    const pageButton = document.createElement('button');
    pageButton.textContent = i;
    pageButton.addEventListener('click', () => {
      currentPage = i;
      const paginatedData = paginateData(data, currentPage, rowsPerPage);
      renderTableView(paginatedData);
    });
    paginationDiv.appendChild(pageButton);
  }

  const container = document.getElementById('tableViewContainer');
  container.appendChild(paginationDiv);
}

const totalPages = Math.ceil(data.length / rowsPerPage);
renderPaginationControls(totalPages);

添加搜索过滤功能

实现搜索框来过滤表格数据,提高数据查找效率。

js实现tableview

<input type="text" id="searchInput" placeholder="Search...">
const searchInput = document.getElementById('searchInput');

searchInput.addEventListener('input', (e) => {
  const searchTerm = e.target.value.toLowerCase();
  const filteredData = data.filter(item => 
    item.name.toLowerCase().includes(searchTerm) ||
    item.email.toLowerCase().includes(searchTerm)
  );
  renderTableView(filteredData);
});

响应式设计优化

通过 CSS 媒体查询确保 TableView 在不同设备上都能良好显示。

@media (max-width: 600px) {
  #tableView {
    width: 100%;
  }

  #tableView th, #tableView td {
    padding: 8px 4px;
    font-size: 14px;
  }
}

性能优化技巧

对于大型数据集,采用虚拟滚动技术可以显著提高性能。

function renderVirtualScroll(data, containerHeight, rowHeight) {
  const visibleRows = Math.ceil(containerHeight / rowHeight);
  let startIndex = 0;

  function updateVisibleRows() {
    const scrollTop = container.scrollTop;
    startIndex = Math.floor(scrollTop / rowHeight);
    const endIndex = startIndex + visibleRows;

    const visibleData = data.slice(startIndex, endIndex);
    renderTableView(visibleData);

    // Adjust padding to maintain scroll height
    const tbody = document.querySelector('#tableView tbody');
    tbody.style.paddingTop = `${startIndex * rowHeight}px`;
    tbody.style.paddingBottom = `${(data.length - endIndex) * rowHeight}px`;
  }

  const container = document.getElementById('tableViewContainer');
  container.style.height = `${containerHeight}px`;
  container.style.overflowY = 'auto';
  container.addEventListener('scroll', updateVisibleRows);

  // Initial render
  updateVisibleRows();
}

// Usage example with 1000 items
const largeData = Array.from({ length: 1000 }, (_, i) => ({
  name: `User ${i + 1}`,
  age: Math.floor(Math.random() * 50) + 18,
  email: `user${i + 1}@example.com`
}));

renderVirtualScroll(largeData, 500, 50);

标签: jstableview
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableElem…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="sli…

js实现复制到剪贴板

js实现复制到剪贴板

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