【问题标题】:pure javascript, filter box doesn't filter properly纯javascript,过滤框无法正确过滤
【发布时间】:2019-05-28 07:31:08
【问题描述】:

我有一个设备数组,每个设备都有自己唯一的 id,我希望创建一个 searchBox 来过滤这个 id。到目前为止,我对它进行了部分管理,因此它会检查输入中的字符是否与设备 ID 中的字符匹配。但是不是我想要的,下面的例子:

id =35678; input.value = 5

它不应该工作,因为第一个字符是3

id = 35679;输入值= 35

第一个字符应该是一样的

问题在于匹配/包含函数,但不知道如何替换它以使其工作

input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"    
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"    
        }
     })
 })

【问题讨论】:

    标签: javascript arrays filter match


    【解决方案1】:

    您可以使用startsWith 代替匹配

    let arr = ['35678', '451234', '45454', '56565']
    
    let find = (value) =>{
      return arr.filter(id=> id.startsWith(value))
    }
    
    console.log(find(5))
    console.log(find(35))
    console.log(find(46))

    【讨论】:

      【解决方案2】:

      您可以简单地使用.indexOf 并检查索引,而不是使用.match,如果它为0,则输入的字符串从一开始就与设备名称匹配。

      array_of_devices.forEach(el => {
        // Condition below is changed to use indexOf
        if (el.indexOf(search_result) === 0) {
          var not_matched = document.querySelector(`[device_id="${el}"]`)
          not_matched.style.display = "none"
        } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"
        }
      });
      

      我建议您根据搜索字符串构建一串设备元素并将其添加到您的 DOM 中,而不是修改显示属性。这会花费您大量计算量很大的 DOM 操作。

      【讨论】:

      • 我觉得它很简单,但无法理解,它工作正常!谢谢:)
      【解决方案3】:

      注意数组中的每个id都应该是字符串

      const ids = ['3575', '5555']
      const found = value => ids.filter(i => i.indexOf(value, 0) === 0)
      console.log(found(5));
      console.log(found(35));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        相关资源
        最近更新 更多