У меня есть простой сайт, который получает список книг из API Google Книг. У меня есть отдельный файл с именем scripts.js, который получает всю информацию о книге (название, автор, ISBN, ссылку на изображение).
Я хочу создать div для каждой книги на странице стиля галереи, где есть изображение книги, а в верхней части книги - название, автор и ISBN.
Я пытался создать DIV в Javascript, но я хочу, чтобы внутри каждого DIV были h3, p и img, и я не могу понять, как я мог бы сделать это в Javascript.
Мой HTML-код для галереи:
<div id = "content">
<h2>My Bookshelf</h2>
<div class = "book">
<!-- The book image is the background of the div -->
<h3 class = "book-title">Title</h3>
<p class = "book-isbn">ISBN: 000000</p>
<p class = "book-author">Authors: ABC</p>
</div>
</div>
Мой код Javascript, который циклически проходит через файл JSON и возвращает необходимую информацию.
// Returns an array with the book title, ISBN, author, bookmark icon, description, image
apiRequest.onreadystatechange = () => {
if (apiRequest.readyState === 4) {
const response = JSON.parse(apiRequest.response);
var bookList = response.items;
// Removes old search results before display new ones
bookSection.innerHTML = "";
for (let i = 0; i < bookList.length; i++) {
console.info(i);
var title = (bookList[i]["volumeInfo"]["title"]);
try {
var isbn = (bookList[i]["volumeInfo"]["industryIdentifiers"][0]["identifier"]);
} catch (TypeError) {
var isbn = "ISBN Not Available";
}
var author = (bookList[i]["volumeInfo"]["authors"]);
var description = (bookList[i]["description"]);
try {
var image = (bookList[i]["volumeInfo"]["imageLinks"]["thumbnail"]);
} catch (TypeError) {
var image = "img/unavailable.png";
}
}
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете использовать литералы шаблонов, чтобы облегчить себе работу.
Вы можете сделать это следующим образом:
var bookSection = `<div id = "content">
<h2>My Bookshelf</h2>
<div class = "book">
<!-- The book image is the background of the div -->
<h3 class = "book-title">${titleVar}</h3>
<p class = "book-isbn">ISBN: ${ISBNVar}</p>
<p class = "book-author">Authors: ${AuthorsVar}</p>
</div>
</div>`;
Узнайте больше о литералах шаблонов здесь: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Ваш код должен выглядеть примерно так
apiRequest.onreadystatechange = () => {
if (apiRequest.readyState === 4) {
const response = JSON.parse(apiRequest.response);
var bookList = response.items;
// Removes old search results before display new ones
bookSection.innerHTML = "";
let bookListHtmlMarkup = '';
for (let i = 0; i < bookList.length; i++) {
console.info(i);
// Declaring book object
const book = {};
const bookListHtmlMarkup = '';
book['title'] = (bookList[i]["volumeInfo"]["title"]);
try {
book['isbn'] = (bookList[i]["volumeInfo"]["industryIdentifiers"][0]["identifier"]);
} catch (TypeError) {
book['isbn'] = "ISBN Not Available";
}
book['author'] = (bookList[i]["volumeInfo"]["authors"]);
book['description'] = (bookList[i]["description"]);
try {
book['image'] = (bookList[i]["volumeInfo"]["imageLinks"]["thumbnail"]);
} catch (TypeError) {
book['image'] = "img/unavailable.png";
}
bookListHtmlMarkup += `
<div class = "book">
<div class = "book-image">
<img src = "${book.image}" alt = "Image unavailable" />
</div>
<div class = "book-info">
<h3 class = "book-title">${book.title}</h3>
<p class = "book-isbn">ISBN: ${book.isbn}</p>
<p class = "book-author">Author: ${book.author}</p>
<p class = "book-description">Author: ${book.description}</p>
</div>
</div>
`;
}
// Assigning generated markup to innerHTML of bookSection
bookSection.innerHTML = bookListHtmlMarkup;
}
}