【问题标题】:Search function to look up name of objects in JSON用于在 JSON 中查找对象名称的搜索功能
【发布时间】:2020-07-29 02:38:30
【问题描述】:

JSON 文件:

[
    {
            "destination": "Hawaii",
            "Country": "U.S.A",
            "description": "...etc, etc",
            "images": {
                "image": [
                    "hawaii1.jpg",
                    "hawaii2.jpg",
                    "hawaii3.jpg",
                    "hawaii4.jpg"
                ]
            }
        }, 
    ***about 5 more destinations continuing on***

.JS:

function searchBar() {

   var input = document.getElementById('searchbox').value;
   var name = ["Hawaii", "London", "Bangkok", "Sydney", "Vegas", "Miami"];
   var ul = document.getElementById("cities");  //ul in markup where li of destinations is displayed


   //I know i need to do an if statement in a for loop, just not sure how.
   for (let i = 0; i < name.length; i++){

       if(input == name){
        li[i].style.display = "";
       } else{
        li[i].style.display = "none";
       }

    }
}

我想拥有它,以便在输入名称或国家/地区时,我的 HTML 中的搜索栏会显示该目的地。不知道如何处理这个问题。我正在考虑将名称放入数组中,然后将其与“搜索框”值进行比较??

JSON 对象已附加到不同函数中的 h2 元素,然后附加到 li 元素中。 抱歉,我遗漏了很多代码,如果您需要更多信息,请告诉我。

【问题讨论】:

    标签: javascript html arrays json dom


    【解决方案1】:

    为了监听input 事件,你需要添加一个监听器,然后你可以监听keyup。一旦您知道有人输入了某些内容,您就想检查您拥有的数据并检查它是否与对象的任何 destinationCountry 值匹配。

    如果是这样,那么只需将一个列表项附加到当前的无序列表中,就像这样:

    let data = [{
      destination: "Hawaii",
      Country: "U.S.A",
      description: "...etc, etc",
      images: {
        image: ["hawaii1.jpg", "hawaii2.jpg", "hawaii3.jpg", "hawaii4.jpg"],
      },
    }, ];
    
    var input = document.getElementById("searchbox");
    // var name = ["Hawaii", "London", "Bangkok", "Sydney", "Vegas", "Miami"];
    var ul = document.getElementById("cities"); //ul in markup where li of destinations is displayed
    
    input.addEventListener("keyup", (e) => {
      let typed = e.target.value.toUpperCase();
      for (let o of data) {
        if (
          typed === o.destination.toUpperCase() ||
          typed === o.Country.toUpperCase()
        ) {
          let li = document.createElement("li");
          li.innerText = JSON.stringify(o);
          ul.append(li);
        }
      }
    });
    <p>Type <code>hawaii</code></p>
    <input type="text" id="searchbox" />
    <ul id="cities"></ul>

    上面的解决方案有一些问题,例如,如果输入被清除,它不会清除ul,或者如果你再次键入相同的国家/目的地,它会继续附加新对象。这些是相对简单的修复,我会留给你,但总的来说,你会想要一些类似的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2015-02-13
      • 2019-07-03
      • 1970-01-01
      相关资源
      最近更新 更多