【问题标题】:How to search number from html table using javascript?如何使用 javascript 从 html 表中搜索数字?
【发布时间】:2022-01-10 09:15:35
【问题描述】:

我在使用 javascript 从 HTML 表中搜索数字时遇到困难。我想要做什么,如果我输入 500 那么结果应该是 500 并且数字也大于 500。 我检查了其他 StackOverflow 问题,但没有像我预期的那样回答。谁能帮帮我?

function myFunction(){
   let filter = document.getElementById('myInput').value;
   let myTable = document.getElementById('myTable');
   let tr = myTable.getElementsByTagName('tr');
   for(var i=0; i<tr.length; i++)
   {
     let td = tr[i].getElementsByTagName('td')[0];
     if(td)
     {
        let textValue = td.textContent || td.innerHTML;
        if(textValue >= filter  )
        {

          tr[i].style.display = "";

        }
        else 
        {
          tr[i].style.display = "none";

        }
     }
   }
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Number</th>
    <th style="width:40%;">Alphabats Code</th>
  </tr>
  <tr>
    <td>500</td>
    <td>ANAA</td>
  </tr>
  <tr>
    <td>520</td>
    <td>MNAAA</td>
  </tr>
  <tr>
    <td>400</td>
    <td>INNA</td>
  </tr>
  <tr>
    <td>200</td>
    <td>OISSS</td>
  </tr>
  <tr>
    <td>500</td>
    <td>QIIWS</td>
  </tr>
</table>

【问题讨论】:

    标签: javascript html search html-table


    【解决方案1】:

    对您的代码稍作改动

    if(+textValue >= +filter  )
    

    将值作为数字而不是字符串进行比较

    function myFunction(){
    
       let filter = document.getElementById('myInput').value;
       let myTable = document.getElementById('myTable');
       let tr = myTable.getElementsByTagName('tr');
       for(var i=0; i<tr.length; i++)
       {
         let td = tr[i].getElementsByTagName('td')[0];
         if(td)
         {
           let textValue = td.textContent || td.innerHTML;
          if(+textValue >= +filter  )
          {
    
            tr[i].style.display = "";
    
          }
          else 
          {
            tr[i].style.display = "none";
          
          }
    
         }
    
       }
    
    
    }
    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
    
    <table id="myTable">
      <tr class="header">
        <th style="width:60%;">Number</th>
        <th style="width:40%;">Alphabats Code</th>
      </tr>
      <tr>
        <td>500</td>
        <td>ANAA</td>
      </tr>
      <tr>
        <td>520</td>
        <td>MNAAA</td>
      </tr>
      <tr>
        <td>400</td>
        <td>INNA</td>
      </tr>
      <tr>
        <td>200</td>
        <td>OISSS</td>
      </tr>
      <tr>
        <td>500</td>
        <td>QIIWS</td>
      </tr>
    
    </table>

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    相关资源
    最近更新 更多