我无法使用脚本在表格视图和网格视图之间切换

问题描述 投票:0回答:1
javascript html css bootstrap-4
1个回答
0
投票

这不起作用的原因是,您有两个包含列表和网格图标的相同 html 标头实例。当您添加事件侦听器时,它仅添加到第一个找到的列表和网格图标。

解决此问题的快速方法是将事件侦听器添加到所有列表和网格图标。

document.addEventListener("DOMContentLoaded", function() {
  // Get the list icon and grid icon elements
  var listIcons = document.querySelectorAll(".fa-solid.fa-list-ul");
  var gridIcons = document.querySelectorAll(
    ".iconsax[icon-name='grid-apps']"
  );

  // Add a click event listener to the list icon
  Array.from(listIcons).forEach(function(listIcon) {
    listIcon.addEventListener("click", function() {
      // Show the table view and hide the grid view
      document.querySelector(".table-section").style.display = "block";
      document.querySelector(".grid-section").style.display = "none";
    });
  });

  Array.from(gridIcons).forEach(function(gridIcon) {
    gridIcon.addEventListener("click", function() {
      // Show the grid view and hide the table view
      document.querySelector(".table-section").style.display = "none";
      document.querySelector(".grid-section").style.display = "block";
    });
  });

});

理想的方法是,您应该只有一个标头实例。

© www.soinside.com 2019 - 2024. All rights reserved.