You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码实现搜索Bootstrap表格第二列而非默认第一列内容

解决方案

你只需要修改JS代码中获取表格单元格的索引即可,HTML的占位提示建议同步修改适配搜索逻辑:

核心修改点

  • JS代码里tr[i].getElementsByTagName("td")[0]的索引0对应第一列Name字段,改为索引1就会匹配第二列Country字段
  • 输入框原有placeholder是「Search for names..」,建议改为「搜索国家名称..」更符合当前功能

修改后完整代码

function myFunction() {
  // 声明变量
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // 遍历所有表格行,隐藏不符合搜索条件的行
  for (i = 0; i < tr.length; i++) {
    // 这里把原来的[0]改成[1],获取第二列单元格
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
<!-- 把placeholder修改为对应国家搜索的提示 -->
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索国家名称..">


<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
</table>

内容的提问来源于stack exchange,提问作者Pouya Vaghefi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 15:06:04