简体   繁体   English

使用 Javascript 中的选择框搜索和过滤结果

[英]Search and filter the results with a choice box in Javascript

So I have a form which you can search product listings from but I want to be able to also take in consideration the options in the drop down so like search a product and select a specific shop to search from as well, if you want.所以我有一个表格,您可以从中搜索产品列表,但我希望能够考虑下拉菜单中的选项,例如搜索产品和 select 一个特定的商店,如果你愿意的话。

<form action="#" method="get">
  <input class="search" id='search' type="text" placeholder="Search Deals"></input>
  <select class="custom-select">
    <option selected>All Shops</option>
    <option value="1">Centra</option>
    <option value="2">Tesco</option>
    <option value="3">SuperValu</option>
    <option value="4">Lidl</option>
    <option value="5">Aldi</option>
  </select>
  <button class="btn btn-search" type="button" id='btn-search'  onclick="on()"><i class="fa fa-search pr- 
  2" aria-hidden="true"></i> Search</button>
</form>

And the Javascript shows the results from the json file. Javascript 显示了 json 文件的结果。

const endpoint = "https://gist.githubusercontent.com/valeriu7474/2c200e73338d061363b4e1f7e43310b3/raw/225e0291ea6ef6e5c61a8f81ae4a44db5e318f63/wedrink";

const name = [];
fetch(endpoint).then(blob => blob.json())
.then(data => name.push(...data));

    function findMatches(wordToMatch, name) {
        return name.filter(place => {
            //we need to figure out if the name match
            const regEx = new RegExp(wordToMatch, 'gi');
            return place.name.match(regEx);
         });
    }

function displayMatches() {
  const searchText = document.querySelector('.search').value;
  const matchArray = findMatches(searchText, name);

  const html = matchArray.map(place => {
    const regex = new RegExp(searchText);
    const nameName = place.name.replace(regex, `<span class="hl">${searchText}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `
        <a href="${place.url}" target="_blank">
            <li>
                <span class="name">${nameName} <br> ${(place.price)} <br><br><sup>${shop} ${shop1} ${shop2} ${shop3} ${shop4}</sup></span>
                <img src="${place.imgurl}" alt="Drink Image" height="87.5" width="100">

            </li>
        </a>

    `;
  }).join('') || '<li> No Searches Found </li>';
  suggestions.innerHTML = html; 
};

const suggestions = document.querySelector('.suggestions');

const searchBtn = document.querySelector('.btn-search');
searchBtn.addEventListener('click', displayMatches);

document.getElementById('search').onkeydown = function(event) {
    if (event.keyCode == 13) {
        event.preventDefault();
        displayMatches();
    }
}

Make the following changes:进行以下更改:

1) Set the value attribute of each dropdown option to the start of the URL that should be used as filter. 1) 将每个下拉选项的value属性设置为应用作过滤器的 URL 的开头。

<select class="custom-select">
    <option value="" selected>All Shops</option>
    <option value="https://centra.">Centra</option>
    <option value="https://www.tesco.">Tesco</option>
    <option value="https://shop.supervalu.">SuperValu</option>
    <option value="https://www.lidl.">Lidl</option>
    <option value="https://www.aldi.">Aldi</option>
</select>

2) Add a parameter to your findMatches function, so it can also filter on a shop. 2)在您的findMatches function 中添加一个参数,这样它也可以在商店上过滤。 Note that you can better use the .test method on your RegExp , as it returns a boolean.请注意,您可以更好地在RegExp上使用.test方法,因为它返回 boolean。 Also, you should only define that regex once, outside the loop.此外,您应该只在循环外定义一次该正则表达式。

function findMatches(wordToMatch, searchUrl, name) {
    const regEx = new RegExp(wordToMatch, 'gi');
    return name.filter(place => {
        return regEx.test(place.name) && place.url.startsWith(searchUrl);
    });
}

3) On button press, read out the shop selection, and pass that to the above function: 3)按下按钮,读出商店选择,并将其传递给上述function:

const searchText = document.querySelector('.search').value;
const searchUrl = document.querySelector('.custom-select').value;
const matchArray = findMatches(searchText, searchUrl, name);

Some other remarks:其他一些评论:

I didn't find the HTML element with class suggestions in your question;我没有在您的问题中找到带有 class suggestions的 HTML 元素; make sure you have it.确保你拥有它。

Your HTML references a function on , which is not defined in your script.您的 HTML 引用了 function on ,这在您的脚本中没有定义。 Also, you already bind an event handler in code, so you should remove the onclick attribute.此外,您已经在代码中绑定了一个事件处理程序,因此您应该删除onclick属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM