javascript - 如何从数组创建多个 HTML 元素?

标签 javascript html google-books

我有一个简单的网站,它从 Google Books API 获取图书列表。 我有一个名为 scripts.js 的单独文件,用于获取所有书籍信息(书名、作者、ISBN、图片链接)。

我想在画廊风格的页面中为每本书创建一个 div,其中有一张书的图片,书的顶部是标题、作者和 ISBN。

我尝试过在 Javascript 中创建 DIV,但我希望每个 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.log(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";
                }
            }
        }
    }

最佳答案

您可以使用模板文字来简化您的工作。

你可以这样做:

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

关于javascript - 如何从数组创建多个 HTML 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082864/

相关文章:

javascript - 如何在特定位置获取svg linearGradient的颜色

javascript - 尝试在图表上绘制虚线

javascript - jquery javascript 关于加载变量范围

javascript - Knockout - 将单击绑定(bind)到嵌套数组子元素

javascript - 加载 Div 后调用 javascript 函数

html - 样式属性在嵌套段落元素中不起作用

javascript - 停止冒泡事件 onclick

ios - Google Books Oauth 访问 token 授权错误

javascript - 使用 Google Books API 的推荐结果无关紧要

javascript - jQuery 自动完成菜单单击图像将数据发布到 Express 服务器