Я хочу реализовать функцию панели поиска, я отобразил данные в пользовательском интерфейсе и хочу реализовать функцию поиска.
Код: Выделить всё
let originalDataa = [];
function sort_by_price_asc() {
return function(elem1, elem2) {
if (elem1.price < elem2.price) {
return -1;
} else if (elem1.price > elem2.price) {
return 1;
} else {
return 0;
}
};
}
function sort_by_price_dsc() {
return function(elem1, elem2) {
if (elem1.price > elem2.price) {
return -1;
} else if (elem1.price < elem2.price) {
return 1;
} else {
return 0;
}
};
}
const postsUrl = `https://dummyjson.com/products/`;
async function getPosts() {
let originalData = []
const res = await fetch(postsUrl);
const posts = await res.json();
originalData = posts
originalDataa = posts.products;
console.log(originalDataa)
return originalData;
}
function renderPost(post) {
const section = document.querySelector('.posts');
const postDiv = document.createElement('div');
const postTitle = document.createElement('h1');
const PostPrice = document.createElement('h3');
const PostBrand = document.createElement('h1');
const postDesc = document.createElement('div');
postDesc.innerText = post.description;
postDesc.style.color = "black"
postTitle.innerText = post.title;
PostPrice.innerText = post.price;
// console.log(postTitle);
postDiv.appendChild(postTitle);
postDiv.appendChild(postDesc);
postDiv.appendChild(PostPrice, "price")
section.appendChild(postDiv);
PostBrand.innerText = post.brand
section.appendChild(PostBrand)
const button = document.createElement('button');
button.innerHTML = "Favourite";
section.appendChild(button)
}
async function renderPosts(type) {
const posts = await getPosts();
const temp = posts.products;
if (type === "asc") {
temp.sort(sort_by_price_asc());
for (let x = 0; x < temp.length; x++) {
renderPost(temp[x]);
}
// console.log(temp);
} else {
temp.sort(sort_by_price_dsc());
for (let x = 0; x < temp.length; x++) {
renderPost(temp[x])
}
// console.log(temp)
}
}
function sortData(type) {
renderPosts(type)
}
function fetchdata() {
let x = document.getElementById("search-box")
console.log(x);
const answer = originalDataa;
for (let i = 0; i < answer.length; i++) {
if (answer[i].title === x) {
renderPost(answer[i]);
}
}
}
Код: Выделить всё
Sort
Ascending
Descending
Search
Favorite
Previous
1
2
3
Next
Подробнее здесь: https://stackoverflow.com/questions/785 ... filtered-d