简体   繁体   English

将javascript模板输出到行div内的html页面

[英]output javascript template to html page inside a row div

I have json api which is a list of books with their properties: title, author, etc.. I need to output the data formatted to html. 我有json api,它是具有属性的书的列表:书名,作者等。我需要将格式化为html的数据输出。 I'm using es6 backtics for this and javascript templating. 我为此使用es6 backtics和javascript模板。 But the problem I'm encountering is that the output is not one iterationg to html page, but every two iteration. 但是我遇到的问题是输出不是一次迭代到html页面,而是每两次迭代。 every single object from json goes into an html card. json中的每个对象都进入html卡。 But my page requires two cards per row. 但是我的页面每行需要两张卡片。 so I need to insert an opening row div every two iteration and an closing row div every two iteration, so that in between the opening row and closing div I have the two cards. 所以我需要每两个迭代插入一个开始行div,然后每两个迭代插入一个关闭行div,以便在开始行和关闭div之间插入两张卡片。 I first thought to put my template in a variable, but that didn't work. 我首先想到将模板放在变量中,但这没有用。 Second I put it in a function with return statement. 其次,我将其放入带有return语句的函数中。 this time work, but I can properly insert the row tags... could someone suggest proper easier way to do this? 这次可以工作,但是我可以正确地插入行标记...有人可以建议这样做的正确方法吗? thanks here's the index.html page. 谢谢,这是index.html页面。 the two cards are in one row. 两张卡成一排。 I don't know before hand how many card I will need. 我事先不知道我需要多少张卡。 the output will be posted to list-ouput id. 输出将发布到列表输出ID。

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Book Finder</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div id="title" class="center">
        <h1 class="text-center mt-5">Book Finder</h1>
        <div class="row">
          <div id="input" class="input-group mx-auto col-lg-6 col-md-8 col-sm-12">
            <input id="search-box" type="text" class="form-control"  placeholder="Search Books!...">
            <button id="search" class="btn btn-primary" onclick="">Search</button>
        </div>
        </div>
      </div>
      <div class="book-list" >
        <h2 class="text-center">Search Result</h2>
        <div id="list-output" class="">
          <div class="row">
            <!-- card  -->
            <div class="col-lg-6">
              <div class="card" style="">
                <div class="row no-gutters">
                  <div class="col-md-4">
                    <img src="" class="card-img" alt="...">
                  </div>
                  <div class="col-md-8">
                    <div class="card-body">
                      <h5 class="card-title">Book Title</h5>
                      <p class="card-text">Author</p>
                      <p class="card-text"><small class="text-muted">Publisher: </small></p>
                      <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- card  -->
            <div class="col-lg-6">
              <div class="card" style="">
                <div class="row no-gutters">
                  <div class="col-md-4">
                    <img src="" class="card-img" alt="...">
                  </div>
                  <div class="col-md-8">
                    <div class="card-body">
                      <h5 class="card-title">Book Title</h5>
                      <p class="card-text">Author</p>
                      <p class="card-text"><small class="text-muted">Publisher: </small></p>
                      <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>

        </div>
      </div>
    </div>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="/css/style.css">
    <!-- <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> -->
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="js/index.js"></script>
  </body>
</html>

 $(document).ready(function() { var item, tile, author, publisher, bookLink, bookImg; var outputList = document.getElementById("list-output"); //listener for search button $("#search").click(function() { $("#title").animate({'margin-top': '5px'}, 1000); // $(".book-list").css("visibility", "visible"); var searchData = $("#search-box").val(); if(searchData === "") { // dsiplayErr(); } else { console.log(searchData); $.get("https://www.googleapis.com/books/v1/volumes?q="+searchData, function(response) { for (var i = 0; i < response.items.length; i++) { item = response.items[i]; title = item.volumeInfo.title; author = item.volumeInfo.authors; publisher = item.volumeInfo.publisher; bookLink = item.selfLink; bookImg = item.volumeInfo.imageLinks.thumbnail; // in production code, item.text should have the HTML entities escaped. if( (i+2) % 2 != 0) { console.log("odd") outputList.innerHTML += `<div class="row">`; } outputList.innerHTML += formatOutput(title, author, bookLink, bookImg); if((i+2) % 2 == 0) { console.log("even") outputList.innerHTML += `</div>`; } console.log(outputList.innerHTML); } }); } }); }); function formatOutput(title, author, publisher, bookLink, bookImg) { // console.log(title + ""+ author +" "+ publisher +" "+ bookLink+" "+ bookImg) var htmlCard1 = `<div class="col-lg-6"> <div class="card" style=""> <div class="row no-gutters"> <div class="col-md-4"> <img src="${bookImg}" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">${title}</h5> <p class="card-text">Author: ${author}</p> <p class="card-text"><small class="text-muted">Publisher: ${publisher}</small></p> </div> </div> </div> </div> </div>` return htmlCard1; } 

I removed few lines which i thought were unnecessary but you can add them back if you want. 我删除了我认为不必要的几行,但是如果需要,您可以将其添加回去。 Following code should be working as you expected 以下代码应按预期工作

       $(document).ready(function () {
            var item, tile, author, publisher, bookLink, bookImg;
            var outputList = $("#list-output");

            //listener for search button
            $("#search").click(function () {
                var searchData = $("#search-box").val();
                if (searchData === "") {
                    // dsiplayErr();
                } else {
                    console.log(searchData);
                    $.get("https://www.googleapis.com/books/v1/volumes?q=" + searchData, function (response) {
                        for (var i = 0; i < response.items.length; i++) {
                            item = response.items[i];
                            title = item.volumeInfo.title;
                            author = item.volumeInfo.authors;
                            publisher = item.volumeInfo.publisher;
                            bookLink = item.selfLink;
                            bookImg = item.volumeInfo.imageLinks.thumbnail;
                            // in production code, item.text should have the HTML entities escaped.
                            var html;
                            if ((response.items.length % 2 != 0) && (i == response.items.length - 1)) {
                                html = "";
                                html += "<div class='row'>";
                                html += formatOutput(title, author, publisher, bookLink, bookImg);
                                html += "</div>";
                                outputList.append(html);
                            }
                            else {
                                if (i % 2 == 0) {
                                    html = "";
                                    html += "<div class='row'>";
                                }

                                html += formatOutput(title, author, publisher, bookLink, bookImg);

                                if (i % 2 != 0) {
                                    html += "</div>";
                                    outputList.append(html);
                                }
                            }
                        }
                    });
                }
            });

        });



        function formatOutput(title, author, publisher, bookLink, bookImg) {
            // console.log(title + ""+ author +" "+ publisher +" "+ bookLink+" "+ bookImg)
                var htmlCard1 = `<div class="col-lg-6">
                <div class="card" style="">
                  <div class="row no-gutters">
                    <div class="col-md-4">
                      <img src="${bookImg}" class="card-img" alt="...">
                    </div>
                    <div class="col-md-8">
                      <div class="card-body">
                        <h5 class="card-title">${title}</h5>
                        <p class="card-text">Author: ${author}</p>
                        <p class="card-text"><small class="text-muted">Publisher: ${publisher}</small></p>
                        <a href="${bookLink}" class="btn btn-secondary">More Info</a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>`
            return htmlCard1;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM