我學習 Javascript 的時間很短,為了吸收我所獲得的知識,我正在開展一個電子商務專案。我想從輸入中創建一個搜索過濾器,以便它只向我顯示用戶想要的產品,我想從包含所有產品的 .Json 檔案中讀取它。
我只向您展示 Json 檔案的一部分:
[
{
"id": 1,
"title": "Intel Core i5 11400",
"price": 28190,
"imageUrl": "../images/productos/procesadores/intel-2.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 2,
"title": "Intel Core i5 11400F",
"price": 22210,
"imageUrl": "../images/productos/procesadores/intel-1.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 3,
"title": " Intel Core i5 11600KF",
"price": 33650,
"imageUrl": "../images/productos/procesadores/intel-2.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
},
{
"id": 4,
"title": "Intel Core i5 12400",
"price": 37068,
"imageUrl": "../images/productos/procesadores/intel-6.jpg",
"description": "Socket 1700 12th Gen"
},
{
"id": 5,
"title": "Intel Core i7 11700K",
"price": 55009,
"imageUrl": "../images/productos/procesadores/intel-3.jpg",
"description": "Socket 1200 11th Gen Rocket Lake"
}
]
我通過 fetch 將其稱為 Js:
const fetchData = async() => {
try{
const res = await fetch("./productos.json");
const data = await res.json();
} catch(error){
console.log(error);
}
}
我想知道的是如何做到這一點,以便用戶每次搜索某些東西時,螢屏上只會出現那些產品,感謝閱讀。
uj5u.com熱心網友回復:
您可以根據用戶搜索的內容輕松地對“資料”陣列應用過濾器。假設用戶將按標題搜索,您可以執行以下操作:
const selectedData = data.filter((item) => item.title.indexof("search text") > -1);
uj5u.com熱心網友回復:
您可以使用 ajax 獲取 JSON 檔案并選擇所需的特定欄位。
$.ajax({
type: "GET",
url: "processor.json",
dataType: "json",
async: false,
success: function(response) {
var title = response.title;
var price = response.price;
console.log(title);
console.log(price);
// And so on with the others fields
}
});
uj5u.com熱心網友回復:
請查看本教程,它解釋了你想要什么。
https://www.w3schools.com/howto/howto_js_filter_lists.asp
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/493434.html
標籤:javascript html css 搜索 筛选