[英]JS/ How to search with input by firstname and lastname but also work if i type space after firstname
let input = document.getElementById('searchInput')
let searchField = document.getElementById('searchField')
input.addEventListener('keyup', (e) => {
const string = e.target.value
const filteredUsers = users.filter((user) => {
if (string != '') {
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {
return user
} else {
searchField.innerHTML = ''
}
} else {
searchField.innerHTML = ''
}
})
filteredUsers.map(user => {
personImg = user.picture.thumbnail
person = user.name.first + ' ' + user.name.last
searchField.innerHTML += `<li class="list-group-item"><img src='${personImg}'>${person}</li>`
})})
我設法編寫了一個搜索 function,它返回獲取的用戶圖片、名字和姓氏。 搜索是按名字和姓氏進行的。 但是,在輸入名字后,如果我顯示了多個選項,如果我按空格鍵輸入我選擇的姓氏,它就會中斷。 我如何實施它才能工作?
替換這個:
const string = e.target.value
if (user.name.first.toLowerCase().includes(string) || user.name.last.toLowerCase().includes(string)) {
有了這個:
const q1 = e.target.value.split(' ')[0]
const q2 = e.target.value.split(' ')[1]
if (user.name.first.toLowerCase().includes(q1) && (!q2 || user.name.last.toLowerCase().includes(q2))) {}
這樣,它將John Doe
拆分為John
和Doe
,並在名字中搜索John
,在姓氏中搜索Doe
。 ( !q2 ||
適用於搜索查詢僅包含名字的情況。)
這是更完整的答案:
// mock user data
let user = {name: {first: 'John', last: 'Doe'}}
// mock event
let e = {target: {value: 'John D'}}
// searched queries
const q1 = e.target.value.toLowerCase().split(' ')[0]
const q2 = e.target.value.toLowerCase().split(' ')[1]
let matched = false;
const first = user.name.first.toLowerCase();
const last = user.name.last.toLowerCase();
if(!q2){
// when we entered just `John`,
// then we should match all first names or last names containing `John`
if(first.includes(q1) || last.includes(q1)) matched = true;
}else{
// when we entered just `John D`, first name should match `John` and last name should match `D`.
if(first.includes(q1) && last.includes(q2)) matched = true;
}
if (matched) {}
此外,如果名稱可能有更多塊(如: John Doe Smith
),您可以將搜索字符串拆分為塊,並在名稱內搜索它們,並對結果進行排序。 就像是:
let foundUser = undefined;
e.target.value.split(' ').forEach(q => {
if (user.name.first.toLowerCase().includes(q) ||
user.name.last.toLowerCase().includes(q)) {
foundUser = user;
}
})
if(foundUser){...}else{...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.