У меня есть школьный проект, и на данный момент я действительно застрял. Когда я смотрю журнал консоли, ошибок нет, если я не пытаюсь вызвать функцию updatePreview. Он вызывает массив, к которому я пытаюсь получить доступ, но не будет добавлять.
const BASE_URL = "https://api.harvardartmuseums.org"; // API
const KEY = "apikey=24ee2a20-b0ec-11ea-b0f6-a19e3f09e261"; // PERSONAL KEY
//MAIN FETCH FUNCTION
async function fetchObjects() {
const url = `${BASE_URL}/object?${KEY}`; //brings data in from API
try {
const response = await fetch(url); //fetches the data
const data = await response.json(); //waits for data
return data; //returns data
} catch (error) {
console.error(error); //console log error
}
}
function onFetchStart() {
$("#loading").addClass("active");
}
function onFetchEnd() {
$("#loading").removeClass("active");
}
fetchObjects().then((fetchTest) => console.log(fetchTest)); // { info: {}, records: [{}, {},]}
//**********FETCHING CATEGORY LISTS**********
//FETCHING CENTURIES
async function fetchAllCenturies() {
const url = `${BASE_URL}/CENTURY?${KEY}&size=100&sort=temporalorder`;
if (localStorage.getItem("centuries")) {
return JSON.parse(localStorage.getItem("centuries"));
}
try {
const response = await fetch(url);
const { records } = await response.json();
localStorage.setItem("centuries", JSON.stringify(records));
return records;
} catch (error) {
console.error(error);
}
onFetchEnd();
onFetchStart();
}
fetchAllCenturies();
//FETCHING CLASSIFICATIONS
async function fetchAllClassification() {
const url = `${BASE_URL}/classification?${KEY}&size=100&sort=name`;
if (localStorage.getItem("classification")) {
return JSON.parse(localStorage.getItem("classification"));
}
try {
const response = await fetch(url);
const { records } = await response.json();
localStorage.setItem("classification", JSON.stringify(records));
return records;
} catch (error) {
console.error(error);
}
onFetchEnd();
onFetchStart();
}
fetchAllClassification();
//PREFETCH CATEGORY LIST FUNCTION
async function prefetchCategoryLists() {
try {
const [classifications, centuries] = await Promise.all([
fetchAllClassification(),
fetchAllCenturies(),
]);
$(".classification-count").text(`(${classifications.length})`);
classifications.forEach((classification) => {
$("#select-classification").append(
$(`<option value="${classification.name}">${classification.name}</option>`)
);
});
$(".century-count").text(`(${centuries.length})`);
centuries.forEach((century) => {
$("#select-century").append($(`<option value="${century.name}">${century.name}</option>`));
});
} catch (error) {
console.error(error);
}
}
prefetchCategoryLists();
function buildSearchString() {
const classification = $("#select-classification").val();
const century = $("#select-century").val();
const keywords = $("#keywords").val();
return `${BASE_URL}/object?${KEY}&classification=${classification}&CENTURY=${century}&keyword=${keywords}`;
}
//SEACH CLICK FUNCTION
$("#search").on("submit", async function (event) {
event.preventDefault();
onFetchStart();
try {
const response = await fetch(buildSearchString());
const { records, info } = await response.json();
console.log(records, info);
return records, info;
} catch (error) {
console.error(error);
} finally {
onFetchEnd();
}
});
function renderPreview(record) {
const { description, primaryimageurl, title } = record;
return $(`<div class="object-preview">
<a href="#">
${
primaryimageurl && title
? `<img src="${primaryimageurl}" /><h3>${title}<h3>`
: title
? `<h3>${title}<h3>`
: description
? `<h3>${description}<h3>`
: `<img src="${primaryimageurl}" />`
}
</a>
</div>`).data("record", record);
}
//PAGINATION
function updatePreview(records) {
const root = $("#preview");
const results = root.find(".results");
results.empty();
records.forEach((record) => {
results.append(renderPreview(record));
});
}
updatePreview();
@import url("https://fonts.googleapis.com/css?family=Roboto|Playfair+Display|Roboto+Condensed&display=swap");
* {
border: 0;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#app {
display: grid;
grid-template-columns: 320px 1fr;
grid-template-rows: auto 1fr;
grid-gap: 8px;
height: 100%;
width: 100%;
background-color: black;
}
#search {
grid-row: 1;
grid-column: 1 / -1;
padding: 8px;
display: grid;
grid-gap: 8px;
grid-template-columns: minmax(300px, 1fr) 240px 240px 100px;
font-family: "Staatliches", cursive;
font-size: 16px;
color: rgb(81, 74, 126);
background: black;
border-bottom: 1px solid black;
}
#search h1 {
grid-row: 1;
grid-column: 1 / -1;
color: rgb(81, 74, 126);
font-family: "Metal Mania", cursive;
}
#search fieldset {
display: flex;
flex-direction: column;
}
#search fieldset label {
margin-bottom: 0.5em;
font-size: 1.2em;
}
#search fieldset label span {
margin-bottom: 0.5em;
font-size: 0.8em;
font-weight: bold;
color: black;
margin-left: 4px;
}
#search select {
padding: 4px;
width: 100%;
height: 32px;
font-family: "Staatliches", cursive;
font-size: 1em;
font-weight: 700;
background: #fff;
border: 1px solid black;
border-radius: 8px;
}
#search option {
font-weight: normal;
}
#search input,
#search button {
padding: 4px 8px;
width: 100%;
height: 32px;
font-family: "Staatliches", cursive;
font-size: 1em;
border: 1px solid black;
}
#search button {
align-self: flex-end;
background-color: rgb(81, 74, 126);
color: white;
font-family: "Staatliches", cursive;
}
#preview,
#feature {
font-family: "Staatliches", cursive;
}
#preview {
grid-column: 1;
grid-row: 2;
display: grid;
grid-template-rows: auto minmax(0, 1fr);
overflow-y: hidden;
color: white;
background-color: black;
}
#preview .pagination {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-gap: 8px;
padding: 8px;
border-bottom: 1px solid black;
background-color: black;
}
button:hover {
box-shadow: 0 20px 25px 0 rgb(24, 0, 70);
background-color: rgb(192, 128, 252);
}
.pagination button {
padding: 4px 12px;
font-size: 1rem;
background: rgb(81, 74, 126);
color: white;
cursor: pointer;
font-family: "Staatliches", cursive;
}
.pagination button:disabled {
background: rgb(81, 74, 126);
color: #ffffff;
cursor: none;
font-family: "Staatliches", cursive;
}
.results {
min-height: 0;
overflow-y: scroll;
display: flex;
flex-direction: column;
padding: 8px;
}
.results .object-preview {
display: flex;
flex-direction: column;
box-shadow: 0 2px 6px -3px black;
padding: 8px;
background: white;
}
.results .object-preview:not(:last-of-type) {
margin-bottom: 8px;
}
.results .object-preview img {
width: 100%;
}
#feature {
grid-column: 2;
grid-row: 2;
padding: 8px;
display: flex;
background: rgb(144, 171, 197);
overflow: hidden;
background-image: url("https://img1.goodfon.com/wallpaper/nbig/6/ba/black-dark-vintage-pattern-3872.jpg");
}
.object-feature {
flex-grow: 1;
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
grid-template-rows: auto minmax(0, 1fr);
background: #fff;
box-shadow: 0 4px 12px -3px black;
}
.object-feature > * {
padding: 8px;
}
.object-feature header {
grid-row: 1;
grid-column: 1 / -1;
background: steelblue;
color: white;
text-shadow: 1px 1px 2px black;
border-bottom: 1px solid black;
font-size: 1.4rem;
}
.object-feature .facts {
grid-row: 2;
grid-column: 1;
min-height: 0;
overflow-y: scroll;
font-size: 1.2rem;
display: grid;
grid-gap: 4px 12px;
grid-template-columns: max-content minmax(0, 1fr);
grid-template-rows: repeat(auto-fill, 2em);
}
.object-feature .facts .title {
grid-column: 1;
font-weight: 900;
}
.object-feature .facts .content {
grid-column: 2;
font-weight: 100;
}
.object-feature .photos {
grid-row: 2;
grid-column: 2;
padding: 8px;
overflow-y: scroll;
}
.object-feature img {
width: 100%;
}
.object-feature img:not(:last-of-type) {
margin-bottom: 8px;
}
#loading {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
backdrop-filter: blur(3px);
background: rgba(0, 0, 0, 0.4);
font-family: "Staatliches", cursive;
font-size: 2rem;
text-align: center;
}
#loading .message {
min-width: 480px;
padding: 3rem;
box-shadow: 0 2px 8px black;
background: white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#loading:not(.active) {
display: none;
}
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Harvard Art</title>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link
href="https://fonts.googleapis.com/css2?family=Metal+Mania&family=Staatliches&display=swap"
rel="stylesheet"
/>
<script defer src="app.js"></script>
</head>
<body>
<div id="app">
<form id="search">
<h1>
Search the Harvard Art Collection
</h1>
<fieldset>
<label for="keywords">Query</label>
<input id="keywords" type="text" placeholder="enter keywords..." />
</fieldset>
<fieldset>
<label for="select-classification"
>Classification <span class="classification-count"></span
></label>
<select name="classification" id="select-classification">
<option value="any">Any</option>
</select>
</fieldset>
<fieldset>
<label for="select-century">Century <span class="century-count"></span></label>
<select name="century" id="select-century">
<option value="any">Any</option>
</select>
</fieldset>
<button>SEARCH</button>
</form>
<aside id="preview">
<header class="pagination">
<button disabled class="previous">Previous</button>
<button disabled class="next">Next</button>
</header>
<section class="results"></section>
</aside>
<main id="feature"></main>
</div>
<div id="loading">
<h2 class="message">Searching...</h2>
</div>
</body>
</html>
Я не закончил даже половину этого проекта, но прямо сейчас мне просто нужно, чтобы предварительный просмотр появлялся на боковой панели.
Мои инструкции таковы: возьмите элемент результатов, он соответствует .results внутри root очистите его l oop над записями и добавьте renderPreview После этого вызовите updatePreview после того, как мы успешно извлечем записи. в обратном вызове отправки для панели поиска. Попробуйте выполнить поиск, и вы увидите, что результаты появятся слева.