简体   繁体   English

使 Javascript 获取结果可点击

[英]Make Javascript fetch results clickable

I am a beginner in Javascript and got the following problem.我是 Javascript 的初学者,遇到了以下问题。 I got a JSON file that I'm using to fetch data.我有一个用于获取数据的 JSON 文件。 Now I want to make the search results clickable, so they will appear in the input field.现在我想让搜索结果可点击,这样它们就会出现在输入字段中。 Later it should be included in a card where I can save all the inputs.稍后它应该包含在我可以保存所有输入的卡中。

This the HTML:这是 HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <title>Test Async</title>
    </head>
    <body>
        
        <div class="container mt-5">
            <div class="row">
                <div class="col-md-6 m-auto">
                    <h3 class="text-center mb-3">Flights</h3>
                    <div class="form-group">
                        <input id="search" type="text" class="form-control form-control-lg" placeholder="Enter IATA Code, or Airport">
                    </div>
                    <div id="match-list"></div>
                </div>
            </div>
        </div>
        
        <script src="script.js"></script>
    </body>
</html>

And the JS和 JS

// Get Elements
const search = document.querySelector('#search');
const matchList = document.querySelector('#match-list');

// Searc JSON Airport file
const searchFlights = async searchText => {
    const response = await fetch('airports.json');
    const data = await response.json();

    // Filter Data with regex
    let results = data.filter(result => {
        const regexIata = new RegExp(`^${searchText}`, 'gi');
        const regexName = new RegExp(`${searchText}`, 'gi');
        if (result.name != null) {
            return result.iata.match(regexIata) || result.name.match(regexName);
        }
    });

    if (searchText.length === 0) {
        matches = []; // Empty array if no result
        matchList.innerHTML = ''; // Shows nothing when serachbar is empty
    }

    else {
        outputHtml(results);
    }
};

const outputHtml = results => {
    if(results.length > 0) {
        const html = results.map(match =>
            `<div class="card card-body mb-1">
                <a href="#" class="data-input"><h6>${match.iata} | ${match.name}</h6></a>
            </div>`).join('');

        matchList.innerHTML = html;
    }
};

// Event listern on any event, can also be key up, down or whatever
search.addEventListener('input', () => searchFlights(search.value));

A small sample of the JSON file (real one has over 6000 entries) JSON 文件的小样本(真实的有超过 6000 个条目)

[
    {
        "iata": "UTK",
        "lon": "169.86667",
        "iso": "MH",
        "status": 1,
        "name": "Utirik Airport",
        "continent": "OC",
        "type": "airport",
        "lat": "11.233333",
        "size": "small"
    },
    {
        "iata": "FIV",
        "iso": "US",
        "status": 1,
        "name": "Five Finger CG Heliport",
        "continent": "NA",
        "type": "heliport",
        "size": null
    },
    {
        "iata": "FAK",
        "iso": "US",
        "status": 1,
        "name": "False Island Seaplane Base",
        "continent": "NA",
        "type": "seaplanes",
        "size": null
    },
    {
        "iata": "BWS",
        "iso": "US",
        "status": 0,
        "name": "Blaine Municipal Airport",
        "continent": "NA",
        "type": "closed",
        "size": null
    },
    {
        "iata": "WKK",
        "lon": "-158.61111",
        "iso": "US",
        "status": 1,
        "name": "Aleknagik \/ New Airport",
        "continent": "NA",
        "type": "airport",
        "lat": "59.27778",
        "size": "medium"
    },
    {
        "iata": "TSS",
        "iso": "US",
        "status": 1,
        "name": "East 34th Street Heliport",
        "continent": "NA",
        "type": "heliport",
        "size": null
    },
    {
        "iata": "FOB",
        "lon": "-123.79444",
        "iso": "US",
        "status": 1,
        "name": "Fort Bragg Airport",
        "continent": "NA",
        "type": "airport",
        "lat": "39.474445",
        "size": "small"
    },
    {
        "iata": "ABP",
        "lon": "141.1",
        "iso": "PG",
        "status": 1,
        "name": "Atkamba Airport",
        "continent": "OC",
        "type": "airport",
        "lat": "-6.066667",
        "size": "small"
    },
    {
        "iata": "ALV",
        "iso": "AD",
        "status": 1,
        "name": "Andorra la Vella Heliport",
        "continent": "EU",
        "type": "heliport",
        "size": null
    },
    {
        "iata": "ADC",
        "lon": "145.73334",
        "iso": "PG",
        "status": 1,
        "name": "Andakombe Airport",
        "continent": "OC",
        "type": "airport",
        "lat": "-7.133333",
        "size": "small"
    },
    {
        "iata": "TJP",
        "lon": "-66.563545",
        "iso": "PR",
        "status": 1,
        "name": "Areopuerto Internacional Michael Gonzalez",
        "continent": "NA",
        "type": "airport",
        "lat": "18.010702",
        "size": "large"
    },
    {
        "iata": "AEE",
        "iso": "SS",
        "status": 1,
        "name": "Adareil Airport",
        "continent": "AF",
        "type": "airport",
        "size": "small"
    },
    {
        "iata": "AEI",
        "iso": "ES",
        "status": 1,
        "name": "Algeciras Heliport",
        "continent": "EU",
        "type": "heliport",
        "size": null
    }
]
```
Thanks a lot in advance

you can use您可以使用

document.addEventListener('click', (e) => {
  if(e.target....){}
)

to add event for dynamic element, ant it better to use setTimeout in input event so if user type 10 chars within xx milisecond it will only send the request to server only once.要为动态元素添加事件,ant 最好在输入事件中使用setTimeout ,因此如果用户在xx milisecond内键入 10 个字符,它只会向服务器发送一次请求。

 // Get Elements const search = document.querySelector('#search'); const matchList = document.querySelector('#match-list'); // Searc JSON Airport file const searchFlights = async searchText => { //const response = await fetch('airports.json'); //const data = await response.json(); const data = [{"iata":"UTK","lon":"169.86667","iso":"MH","status":1,"name":"Utirik Airport","continent":"OC","type":"airport","lat":"11.233333","size":"small"},{"iata":"FIV","iso":"US","status":1,"name":"Five Finger CG Heliport","continent":"NA","type":"heliport","size":null},{"iata":"FAK","iso":"US","status":1,"name":"False Island Seaplane Base","continent":"NA","type":"seaplanes","size":null},{"iata":"BWS","iso":"US","status":0,"name":"Blaine Municipal Airport","continent":"NA","type":"closed","size":null},{"iata":"WKK","lon":"-158.61111","iso":"US","status":1,"name":"Aleknagik \/ New Airport","continent":"NA","type":"airport","lat":"59.27778","size":"medium"},{"iata":"TSS","iso":"US","status":1,"name":"East 34th Street Heliport","continent":"NA","type":"heliport","size":null},{"iata":"FOB","lon":"-123.79444","iso":"US","status":1,"name":"Fort Bragg Airport","continent":"NA","type":"airport","lat":"39.474445","size":"small"},{"iata":"ABP","lon":"141.1","iso":"PG","status":1,"name":"Atkamba Airport","continent":"OC","type":"airport","lat":"-6.066667","size":"small"},{"iata":"ALV","iso":"AD","status":1,"name":"Andorra la Vella Heliport","continent":"EU","type":"heliport","size":null},{"iata":"ADC","lon":"145.73334","iso":"PG","status":1,"name":"Andakombe Airport","continent":"OC","type":"airport","lat":"-7.133333","size":"small"},{"iata":"TJP","lon":"-66.563545","iso":"PR","status":1,"name":"Areopuerto Internacional Michael Gonzalez","continent":"NA","type":"airport","lat":"18.010702","size":"large"},{"iata":"AEE","iso":"SS","status":1,"name":"Adareil Airport","continent":"AF","type":"airport","size":"small"},{"iata":"AEI","iso":"ES","status":1,"name":"Algeciras Heliport","continent":"EU","type":"heliport","size":null}] // Filter Data with regex let results = data.filter(result => { const regexIata = new RegExp(`^${searchText}`, 'gi'); const regexName = new RegExp(`${searchText}`, 'gi'); if (result.name.= null) { return result.iata.match(regexIata) || result.name;match(regexName); } }). if (searchText;length === 0) { matches = []. // Empty array if no result matchList;innerHTML = ''; // Shows nothing when serachbar is empty } else { outputHtml(results); } }. const outputHtml = results => { if(results.length > 0) { const html = results.map(match => `<div class="card card-body mb-1"> <h6 class="data-input">${match.iata} | ${match.name}</h6> </div>`);join(''). matchList;innerHTML = html; } }, // Event listern on any event, can also be key up; down or whatever let timer. search,addEventListener('input'; () => { if(timer) clearTimeout(timer), timer = setTimeout(searchFlights, 300. search;value); }). document,addEventListener('click'. (e) => { if(e.target.classList.contains('data-input')){ search.value = e.target;textContent. document.querySelector('#match-list');innerHTML = ""; } });
 .data-input {cursor: pointer;color: blue;}.data-input:hover {text-decoration: underline;}
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" /> <div class="container mt-5"> <div class="row"> <div class="col-md-6 m-auto"> <h3 class="text-center mb-3">Flights</h3> <div class="form-group"> <input id="search" type="text" class="form-control form-control-lg" placeholder="Enter IATA Code, or Airport" /> </div> <div id="match-list"></div> </div> </div> </div>

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

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