返回

JavaScript打造table表格多选模式,解锁高效分页保存数据与记录选择数量

前端

1. HTML结构与CSS样式

首先,我们来构建table表格的基本HTML结构:

<table id="product-table">
  <thead>
    <tr>
      <th><input type="checkbox" id="select-all"></th>
      <th>产品名称</th>
      <th>产品价格</th>
      <th>产品数量</th>
    </tr>
  </thead>
  <tbody>
    <!-- 动态生成产品列表 -->
  </tbody>
</table>

接下来,添加一些CSS样式来美化表格:

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 5px;
  border: 1px solid #ccc;
}

#select-all {
  margin-right: 5px;
}

.selected {
  background-color: #f0f8ff;
}

2. JavaScript实现多选与分页保存

接下来,我们就开始编写JavaScript代码来实现多选与分页保存功能:

// 获取表格元素
const table = document.getElementById('product-table');

// 获取全选复选框元素
const selectAllCheckbox = document.getElementById('select-all');

// 获取分页按钮元素
const paginationButtons = document.querySelectorAll('.pagination-button');

// 获取已选条目数量元素
const selectedCountElement = document.getElementById('selected-count');

// 存储已选产品ID的数组
const selectedProducts = [];

// 添加全选复选框事件监听器
selectAllCheckbox.addEventListener('click', (event) => {
  // 获取所有产品复选框元素
  const productCheckboxes = table.querySelectorAll('input[type="checkbox"]');

  // 根据全选复选框的状态,设置所有产品复选框的状态
  productCheckboxes.forEach((checkbox) => {
    checkbox.checked = event.target.checked;
  });

  // 更新已选条目数量
  updateSelectedCount();
});

// 遍历所有产品复选框元素,添加事件监听器
table.querySelectorAll('input[type="checkbox"]').forEach((checkbox) => {
  checkbox.addEventListener('click', (event) => {
    // 更新已选产品ID数组
    if (event.target.checked) {
      selectedProducts.push(event.target.value);
    } else {
      selectedProducts.splice(selectedProducts.indexOf(event.target.value), 1);
    }

    // 更新已选条目数量
    updateSelectedCount();
  });
});

// 添加分页按钮事件监听器
paginationButtons.forEach((button) => {
  button.addEventListener('click', (event) => {
    // 获取当前页码
    const currentPage = parseInt(event.target.textContent);

    // 保存当前页已选产品ID
    const currentPageSelectedProducts = [];
    table.querySelectorAll('input[type="checkbox"]:checked').forEach((checkbox) => {
      currentPageSelectedProducts.push(checkbox.value);
    });

    // 更新已选产品ID数组
    selectedProducts.length = 0;
    selectedProducts.push(...currentPageSelectedProducts);

    // 更新已选条目数量
    updateSelectedCount();

    // 重新加载表格数据(模拟分页)
    // ...

    // 重新勾选当前页已选产品
    table.querySelectorAll('input[type="checkbox"]').forEach((checkbox) => {
      checkbox.checked = currentPageSelectedProducts.includes(checkbox.value);
    });
  });
});

// 更新已选条目数量
const updateSelectedCount = () => {
  selectedCountElement.textContent = selectedProducts.length;
};

3. 应用与扩展

上述代码演示了如何使用JavaScript实现table表格多选模式,并分页保存已选数据,同时记录下已选条目数量。开发者可以根据实际需求进行扩展,例如实现多页同时选择数据、优化分页加载性能、添加数据验证等。

4. 总结

希望这篇教程能够帮助你轻松构建table表格多选模式,并掌握分页保存数据与记录选择数量的技巧。在前端开发中,掌握好这些技巧可以大大提高你的开发效率,并为用户提供更加流畅和高效的操作体验。