我有一个设备数组,每个设备都有自己唯一的ID,我希望制作searchBox,它将按此ID进行过滤。到目前为止,我已经部分管理了它,因此它检查输入中的字符是否与设备 ID 中的字符匹配。但不是我想要的方式,例如下面的:
id =35678; input.value = 5
它不应该工作,因为第一个字符是3
id = 35679; input.value= 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"
}
})
})
最佳答案
您可以使用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))
关于javascript - 纯javascript,过滤框无法正确过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56337102/