我的搜索功能仅匹配精确的字符串

问题描述 投票:0回答:1

我的搜索方法不起作用。您必须输入搜索正在查找的确切名称才能使其正常工作,否则它不会返回任何内容:

function find(){
    let inputField = document.getElementById("search");
    let value = inputField.value; 
    let getDeriva = value.search("Deriva")
    if(getDeriva == 0){    
        
    }else{
        let getRagno = value.search(" Ragno ")
        if(getRagno == 0){
            document.getElementById("matches").innerHTML = "4 Matches found";
            document.getElementById("demoTwo").innerHTML = "1. Ragno seat skeleton 20¢ No.1";
            document.getElementById("demoThree").innerHTML = "2. Ragno seat trim pcs 50¢ No.3";
            document.getElementById("demoFour").innerHTML = "3. Ragno headrest top skeleton and connection bar 5¢ No.58";
            document.getElementById("demoFive").innerHTML = "4. Ragno luxury sport trim whole seat and Spyder headrest 80¢ No.101";
        }else{
            let getAkalotos = value.search("Akalotos")
            if(getAkalotos == 0){
              
            }else{
                let getVentoor = value.search("Ventoor")
                if(getVentoor==0){
                  
                }else{
                    let getBentaar = value.search("Bentaar")
                    if(getBentaar == 0){
                      
                    }else{
                        document.getElementById("matches").innerHTML = "Nothing Found";
                    }
                }
            }
        }
    }
}

我期望我可以输入

Fillis Ragno
,JavaScript 会为我搜索
Ragno
。但它不起作用,并显示未找到匹配项。

我想让人们找到他们要找的东西,所以我使用了

search
方法;然而,当我把它放进去时,它并没有算作我的搜索,它所做的只是错误的。因此,不知何故,它仍然返回 -1(当未找到值时),而不是 0(当找到该值时)。

javascript database search indexing methods
1个回答
0
投票

也许应该换个角度思考。您可以将结果放在一个数组中,并通过输入的搜索词过滤该数组,而不是检查搜索值并打印静态结果。

const data = [
  "Ragno seat skeleton 20¢ No.1",
  "Ragno seat trim pcs 50¢ No.3",
  "Ragno headrest top skeleton and connection bar 5¢ No.58",
  "Ragno luxury sport trim whole seat and Spyder headrest 80¢ No.101"
];
const searchtermInput = document.querySelector('.searchterm');

searchData = (e) => {
  let searchterm = searchtermInput.value;
  
  let foundData = data;
  if (searchterm != '') {
    foundData = data.filter(entry => entry.toLowerCase().includes(searchterm.trim().toLowerCase()));
  }
  
  console.log(foundData);
}

searchtermInput.addEventListener('input', searchData);
<input type="text" class="searchterm" placeholder="Enter search term">

您可以进一步改进 data.filter 来处理空格分隔的单词,但这取决于您。示例:按空格分割搜索项并针对每个段进行过滤。

© www.soinside.com 2019 - 2024. All rights reserved.