猿问

如何使用 for 循环从 JSON URL 打印所有数据?

当我尝试在 HTML 上输出它时,它不会显示整个输出,而是一个一个国家。


我尝试使用它来输出它,document.write但它会覆盖整个 HTML。如何在不替换所有 HTML 代码的情况下打印所有数据?我还尝试了其他方式来使用getElementById,输出它innerHTML。这些都不起作用。


<!DOCTYPE html>

<html>


<head>

  <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsenui.css">

  <link rel="stylesheet" href="https://unpkg.com/onsenui/css/onsen-css-components.min.css">


  <script src="https://unpkg.com/onsenui/js/onsenui.min.js"></script>

  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

</head>


<body style="color:silver;">


  <ons-page>

    <ons-toolbar>

      <div class="center" style="color:#fff; text-shadow: 1px 1px silver; background-color:#E20000;">CORONA VIRUS TRACKER</div>

    </ons-toolbar>


    <ons-tabbar swipeable position="auto">

      <ons-tab page="tab1.html" label="Global" icon="globe, material:md-home" active>

      </ons-tab>

    </ons-tabbar>

  </ons-page>


  <template id="tab1.html">

  <ons-page id="Tab1">

   <div class="allcountry"></div>

  </ons-page>

</template>


  <script>

    for (var i = 0; i < 199; i++) {

      (function(i) {

        $.getJSON('https://coronavirus-19-api.herokuapp.com/countries', function(data3) {

          var txt = `<table style="border-collapse: collapse; font-family: Andale Mono, monospace; border: silver;" width="100%" border="1">

        <tr><td><div style="background-color: #EB0D0D; text-transform: uppercase; text-align:center; color:#fff;">${data3[i].country}<br></div></td></tr>

        

   

                    <tr><td><img src="https://via.placeholder.com/150" height="90" width="90" style="float: left; padding-right: 5px;"><h5>CONFIRMED CASES</h5> <h3>${data3[i].cases}</h3></td></tr>

                    

                    <tr><td><img src="https://via.placeholder.com/150" height="90" width="90" style="float: left; padding-right: 5px;"><h5>NEW CASES</h5> <h3>${data3[i].todayCases}</h3></td></tr>

                    

                 

          $(".allcountry").html(txt);

        })

      })(i);

    }

  </script>

</body>

</html>


HUWWW
浏览 111回答 1
1回答

慕容森

txt在开始 for 循环之前定义,并在循环完成后显示值。var txt = '';for (var i = 0; i < 199; i++) {&nbsp; &nbsp; // Concatenate the values to txt here&nbsp; &nbsp; txt += '<table....';}$(".allcountry").html(txt);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答