根据Javascript中的值显示/隐藏列

问题描述 投票:0回答:6

我对 javascript 还很缺乏经验,不过我想尝试一下,并且很高兴得到一些支持。我有以下情况:

我有一个表格,有几行和 3 列。第 1 列是名称,第 2 列是数字 (ID),第 3 列是值。

我在 Web 应用程序中有一个值 (ID),我想在第 2 列的表中搜索该值,并且只想显示该行。最好的开始方式是什么?为了实现这一点,我应该更仔细地关注哪些具体主题?我很高兴收到答复!

<div id="datatable" align="center">
    <table>
        <tr id="class1">
            <td>Person 1</td>
            <td>1234561</td>
            <td>800</td>
        </tr>
         <tr id="class1">
            <td>Person 2</td>
            <td>1234562</td>
            <td>1800</td>
        </tr>
         <tr id="class1">
            <td>Person 3</td>
            <td>1234563</td>
            <td>1400</td>
        </tr>
    </table>
</div>

我已经在网上搜索过类似的脚本,但是似乎并不经常需要!所以我现在想自己解决这个问题。但如何开始呢?

javascript jquery filter html-table
6个回答
0
投票

您可以选择

table
并使用
rows
循环遍历其
forEach
并检查
row.cells[1]
(这是 ID 单元格),其文本内容是否以
input
值开头,如果不是则用
display: none 隐藏它
如果匹配则显示
display: table-row

const personTable = document.querySelector('table');
const tableRows = [...personTable.rows];
const input = document.querySelector('input');

input.addEventListener('input', (e) => {
  const value = e.target.value;
  const rows = tableRows.forEach(row => {
    const match = row.cells[1].textContent.trim().startsWith(value.trim())
    if (match) {
      row.style.display = 'table-row'
    } else {
      row.style.display = 'none'
    }
    
  })
})
<div id="datatable" align="center">
    <table id="person-table">
        <tr id="class1">
            <td>Person 1</td>
            <td>1234561</td>
            <td>800</td>
        </tr>
         <tr id="class1">
            <td>Person 2</td>
            <td>1234562</td>
            <td>1800</td>
        </tr>
         <tr id="class1">
            <td>Person 3</td>
            <td>1234563</td>
            <td>1400</td>
        </tr>
    </table>
</div>

<input type="text" />


0
投票

首先,你应该研究 DOM 操作,这样你才能真正 访问和操作必要的值。另外,您应该研究如何与课程一起工作。还需要循环的知识。最后,对 HTML 和 CSS 有一定的了解是必要的。所有这些材料都可以在 W3schools,所以检查那里。

编辑:您没有要求编码解决方案,这就是我不提供它的原因。


0
投票

需要的技能太多了,如果不做的话很难弄清楚。

我改变的一件事是你的数据从 html 变成了数组。我发现一旦您了解了数组,以及如何将它们输出为 HTML,它们的使用就会容易得多。

有很多方法可以做到这一点——了解这一点很重要。这里并没有真正的“正确”答案。

// Arrays https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
const people = [
  { name: "Person 1", num: 1234, details: 800 },
  { name: "Person 2", num: 3456, details: 1800 },
  { name: "Person 3", num: 5678, details: 1400 }
];

// Query selectors — https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
const tbody = document.querySelector("#tbody");
const searchBox = document.querySelector("#search-box");

// * Get the matching items
// Functions https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
const selectList = () => {
  // * If nothing has been typed...
  // Input value https://www.w3schools.com/jsref/prop_text_value.asp
  // if statements https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
  if(searchBox.value == ""){
    return people;
  }
  // Array filtering — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  return people.filter(person => {
    // Converting numbers to strings — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString
    // String includes — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
    return (person.num.toString()).includes(searchBox.value)
  })
}

// * Convert the array into data for the table
const getData = (found) => {
  // * If the result of our filter has no values
  if(found.length == 0){
    return `<tr>
      <td colspan="3">No results found</td>
    </tr>`
  }
  // Otherwise, create the rows
  // Template literals — https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
  return found.map(person => `<tr id="class1">
            <td>${person.name}</td>
            <td>${person.num}</td>
            <td>${person.details}</td>
        </tr>`).join("\n");
}

// Called whenever the textbox changes
const render = () => {
  
  // Get the list
  const found = selectList();
  // Convert to html
  const data = getData(found);
  
  // Empty the body
  tbody.textContent = "";
  
  // Append the new data
  tbody.innerHTML = data;
}

// Event listeners — https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
searchBox.addEventListener('input', render);
render();
<div>
  <input type="text" id="search-box" />
</div>

<div>
  <div id="datatable" align="center">
    <thead>
      <tr>
        <th>Name</th>
        <th>Num</th>
        <th>Details</th>
      </tr>
    </thead>
      <table>
        <tbody id="tbody"></tbody>
      </table>
  </div>
  
</div>


0
投票

要获得快速且不一定肮脏的解决方案,请查看 https://datatables.net/ 。这个库通过表格解决了您的大部分问题或愿望。

因此,您首先在 html 中添加库:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>

然后在您的脚本标签中,初始化表上的数据表并选择表并添加如下功能:

$(document).ready( function () {
    $('#datatable').DataTable();
} );

$('#datatable').DataTable( {
    searching: true,
    paging: false
} );

然后,根据您的学习渴望,一点一点开始学习 JS、DOM、HTML 的基础知识,正如其他人提到的那样。


0
投票

哇,非常感谢你们的回答。这对我帮助很大,我想我不会使用最快的解决方案,而是通过 Mimo JS 部分来扩展我的基本理解。您的方法真的很棒,感谢您的支持!当我准备好时,我会在这里发布我的解决方案。


0
投票

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Show/Hide Columns</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
  <h1>Show/Hide Columns</h1>
  <div class="options">
    <label><input type="checkbox" class="column-toggle" data-column="name" checked> Name</label>
    <label><input type="checkbox" class="column-toggle" data-column="email" checked> Email</label>
    <label><input type="checkbox" class="column-toggle" data-column="phone" checked> Phone</label>
  </div>
  <table id="data-table">
    <thead>
      <tr>
        <th data-column="name">Name</th>
        <th data-column="email">Email</th>
        <th data-column="phone">Phone</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-column="name">John Doe</td>
        <td data-column="email">[email protected]</td>
        <td data-column="phone">123-456-7890</td>
      </tr>
      <!-- More rows here -->
    </tbody>
  </table>
</div>
<script src="script.js"></script>
</body>
</html>

<style>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.options {
  margin-bottom: 10px;
}

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

#data-table th,
#data-table td {
  border: 1px solid #ccc;
  padding: 8px;
}

</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
  const checkboxes = document.querySelectorAll('.column-toggle');
  checkboxes.forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
      const column = this.getAttribute('data-column');
      const th = document.querySelector(`th[data-column="${column}"]`);
      const tdList = document.querySelectorAll(`td[data-column="${column}"]`);

      if (this.checked) {
        th.style.display = '';
        tdList.forEach(function(td) {
          td.style.display = '';
        });
      } else {
        th.style.display = 'none';
        tdList.forEach(function(td) {
          td.style.display = 'none';
        });
      }
    });
  });
});

</script>

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