【问题标题】:theads disappears when searching in table html在表格 html 中搜索时,theads 消失
【发布时间】:2020-10-27 22:20:55
【问题描述】:

你能检查一下这个代码吗?我正在尝试对每个列进行单独搜索,这个代码正在工作,问题是当我搜索广告时消失了。

<style>
body {padding: 20px;}
input {margin-bottom: 5px; padding: 2px 3px; width: 98px;}
td {padding: 4px; border: 1px #CCC solid; width: 100px;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search1" placeholder="Type to search">
<input type="text" id="search2" placeholder="Type to search">
<table id="table">
    <thead>
        <tr>Item</tr>
        <tr>Color</tr>
    </thead>
    <tbody>
        <tr>
            <td>Apple</td>
            <td>Green</td>
        </tr>
        <tr>
            <td>Grapes</td>
            <td>Green</td>
        </tr>
        <tr>
            <td>Orange</td>
            <td>Orange</td>
        </tr>
    </tbody>
</table>

这是搜索脚本。

<script>
var $rows = $('#table tr'),
    searchVal1,
    searchVal2,
    td1,
    td2;

$('input').keyup(function () {
  searchVal1 = $('#search1').val(),
  searchVal2 = $('#search2').val();

  $rows.each(function (index, tr) {
    td1 = $(tr).find('td:nth-of-type(1)').text().toLowerCase(),
    td2 = $(tr).find('td:nth-of-type(2)').text().toLowerCase();

    if ( (td1.indexOf(searchVal1) != -1) && (td2.indexOf(searchVal2) != -1) ) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });

  if ((searchVal1 === '') && (searchVal2 === '')) {
    $rows.show();
  }
});
</script>

我从这个问题得到了代码:How to combine search in table by two input text fields?

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    问题在于$('#table tr') 会从表中获取所有行,包括第一行(表头)。你应该排除它。

    <script>
    var $rows = $('#table tr:not(:first)'),
        searchVal1,
        searchVal2,
        td1,
        td2;
    
    $('input').keyup(function () {
      searchVal1 = $('#search1').val(),
      searchVal2 = $('#search2').val();
    
      $rows.each(function (index, tr) {
        td1 = $(tr).find('td:nth-of-type(1)').text().toLowerCase(),
        td2 = $(tr).find('td:nth-of-type(2)').text().toLowerCase();
    
        if ( (td1.indexOf(searchVal1) != -1) && (td2.indexOf(searchVal2) != -1) ) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    
      if ((searchVal1 === '') && (searchVal2 === '')) {
        $rows.show();
      }
    });
    </script>

    另一种方法是使用$('#table tbody tr') - 获取 tbody 中的所有行(没有标题行)

    另外,使用&lt;th&gt; 代替&lt;tr&gt; 作为表头

    【讨论】:

    • 如果我的解决方案对您有帮助,请将其标记为已接受
    猜你喜欢
    • 2019-10-14
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多