【问题标题】:how to add a table filter in the code snippets in javascript?如何在javascript的代码片段中添加表格过滤器?
【发布时间】:2020-10-03 20:39:08
【问题描述】:

您好,我已经将所有代码放入链接中,但我不知道如何为名称添加过滤器:https://codepen.io/nutkin/pen/yLOmzom 该表是使用 javascript 中的循环从 json 对象创建的,我可以搜索很多关于如何在 jquery 或 reactjs 中修复它的答案,但我真的很想知道如何在 javascript 中摆弄这个。 让我举个例子:如果用户输入'F'或'f',屏幕应该过滤所有带有'f'和'F'的名字,谢谢大家。下面是代码:

var myContacts = [
    {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
    {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
    {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
    {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
    {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
    {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
  ];
  function generateTable(){
    var table=document.createElement('table');
    table.style.width='50%';
   
    table.setAttribute('cellspacing','0');
    table.setAttribute('cellpading','5');
    var col=[];
    for(var i=0;i<myContacts.length;i++){
      for(var key in myContacts[i]){
        if(col.indexOf(key)===-1){
          col.push(key);
        }
      }
    }
    var tHead=document.createElement('thead');
    var hRow=document.createElement('tr');
    for(var i=col.length-3;i<col.length;i++)
      {
        if(col[i]!='stocked')
        {
          var th=document.createElement('th');
      th.innerHTML=col[i];
      hRow.appendChild(th);
      }    
      }
    tHead.appendChild(hRow);
    table.appendChild(tHead);

    var tBody=document.createElement('tbody');
    for(var i=0;i<myContacts.length;i++)
    {
      var bRow=document.createElement('tr');
      var y=document.createElement('td');
      var t=document.createTextNode(myContacts[i].name);
      y.appendChild(t);
     
      var z=document.createElement('tr');
      var s=document.createTextNode(myContacts[i].price);
      z.appendChild(s);
      bRow.appendChild(y);
      bRow.appendChild(z);
      tBody.appendChild(bRow);
      if(myContacts[i].stocked===false)
      {
        y.style.color='red';

      }
    }
   
    table.appendChild(tBody);
    var divContainer=document.getElementById('tableroom');
    divContainer.innerHTML='';
    divContainer.appendChild(table);
}
<body onload="generateTable()">
  <input type="text"  name="search" id="searchBar" placeholder="Search..">  
  <div id='chechbox'>
      <input type="checkbox" id='searchBox'>Only show products in stock
  </div>
  <div id="tableroom" ></div>
</body>

【问题讨论】:

    标签: javascript json filter


    【解决方案1】:

    类似的东西?

    const myContacts = 
        [ { category: 'Sporting Goods', price: "$49.99",  stocked: true,  name: "Football"   } 
        , { category: 'Sporting Goods', price: "$9.99",   stocked: true,  name: "Baseball"   } 
        , { category: 'Sporting Goods', price: '$29.99',  stocked: false, name: 'Basketball' } 
        , { category: 'Electronics',    price: '$99.99',  stocked: true,  name: 'iPod Touch' } 
        , { category: 'Electronics',    price: '$399.99', stocked: false, name: 'iPhone 5'   } 
        , { category: 'Electronics',    price: '$199.99', stocked: true,  name: 'Nexus 7'    } 
        ] 
    
    const info = 
      { room : document.getElementById('tableroom')
      , table : null
      };
    const chkOnlyStock = document.getElementById('chk-onlyStock')
      ,   searchBar    = document.getElementById('search-bar')
      ;
    (function() // IIFE generateTable
      {
      let eTable = document.createElement('table')
    
      myContacts.forEach(contact=>
        {
        let row = eTable.insertRow()
    
        let c_Name  = row.insertCell()
        c_Name.textContent = contact.name
        c_Name.className   = contact.stocked ? '' : 'noStock'
    
        row.insertCell().textContent = contact.price
        })
    
      let rowHead = eTable.createTHead().insertRow()
      rowHead.insertCell().textContent = 'Name'
      rowHead.insertCell().textContent = 'Price'
      
      info.room.appendChild(eTable)
      info.table = info.room.querySelector('tbody')
      })()
    
    function rowShow()
      {
      let showAll = (searchBar.value === '')
      if (/^[a-zA-Z]+$/.test(searchBar.value)  || showAll )  // accept only characters
        {
        let reg = new RegExp(searchBar.value, 'ig')
          ; 
        info.table.querySelectorAll('tr').forEach(row=>
          {
          let stockOk   = !(chkOnlyStock.checked && row.cells[0].classList.contains('noStock'))
            , letterOK  = reg.test(row.cells[0].textContent)
            ;
          reg.lastIndex = 0;
          row.className = (( letterOK || showAll) && stockOk) ? '' : 'noDisplay'
          })
        }
      else searchBar.value = '' // otherwise reset!
      }
    
    chkOnlyStock.onchange = rowShow
    searchBar.oninput     = rowShow
    table {
      border-collapse: collapse;
      margin: .5em;
    }
    thead {
      font-weight: bold;
      background-color: #978aec;
      text-align: center;
    }
    td {
      padding: .2em .7em;
      border: 1px solid black;
    }
    td:nth-of-type(2)  {
      text-align: right;
    }
    .noStock {
      color: red;
    }
    .noDisplay {
      display: none;
    }
    <input type="text"  name="search" id="search-bar" placeholder="Search..">  
    <br>
    <label> <input type="checkbox" id='chk-onlyStock'>Only show products in stock </label>
    <br>
    <div id="tableroom"></div>

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 2017-09-06
      • 2017-10-01
      • 2018-10-20
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2019-04-05
      • 2022-11-02
      相关资源
      最近更新 更多