代码之家  ›  专栏  ›  技术社区  ›  Jack Bashford

如何使用jQuery插入多个HTML元素

  •  2
  • Jack Bashford  · 技术社区  · 6 年前

    我有一个网页,正在从雅虎获取数据!天气API。我在用 this query . 我想使用jQuery构建一个表,它插入带有id的元素。这是我当前的代码:

    $.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22canberra%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", function(data) {
      $("#title").append(data.query.results.channel.title);
      $("#sunrise").append(data.query.results.channel.astronomy.sunrise);
      $("#sunset").append(data.query.results.channel.astronomy.sunset);
      $("#title-2").append(data.query.results.channel.item.title);
      for (var i = 0; i < 10; i += 1) {
        var newRow = $("<tr></tr>").attr("id", "row-" + (i + 1));
        var newDate = $("<td></td>").attr("id", "date-" + (i + 1));
        var newMin = $("<td></td>").attr("id", "min-" + (i + 1));
        var newMax = $("<td></td>").attr("id", "max-" + (i + 1));
        var newConditions = $("<td></td>").attr("id", "conditions-" + (i + 1));
        $("#weather").append(newRow);
        $("#row-" + (i + 1)).append(newDate, newMin, newMax, newConditions);
        $("#date-" + (i + 1)).append(data.query.results.channel.item.forecast[i].day + " " + data.query.results.channel.item.forecast[i].date);
        $("#min-" + (i + 1)).append((Math.floor(((data.query.results.channel.item.forecast[i].low) - 32) / 1.8)) + "°C");
        $("#max-" + (i + 1)).append((Math.floor(((data.query.results.channel.item.forecast[i].high) - 32) / 1.8)) + "°C");
        $("#conditions-" + (i + 1)).append(data.query.results.channel.item.forecast[i].text);
      }
      $("#lastBuild").append(data.query.results.channel.lastBuildDate);
    }, "json");
    div#main {
      width: 595px;
    }
    table#weather {
      border-collapse: collapse;
      width: 595px;
    }
    table#headers {
      width: 595px;
    }
    td,
    th {
      width: 148.75px;
      text-align: center;
    }
    tr {
      height: 28px;
    }
    <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    
    <div id="main">
      <h1 id="title"></h1>
      <ul id="sun">
        <li id="sunrise"><strong>Sunrise: </strong></li>
        <li id="sunset"><strong>Sunset: </strong></li>
      </ul>
      <h2 id="title-2"></h2>
      <table id="headers">
        <tr>
          <th id="date">Date</th>
          <th id="min">Min</th>
          <th id="max">Max</th>
          <th id="conditions">Conditions</th>
        </tr>
      </table>
      <table id="weather" border="1"></table>
      <br />
    </div>
    <em id="lastBuild">Data last built at: </em>

    我的问题是:

    1 回复  |  直到 6 年前
        1
  •  1
  •   Chan MT    6 年前

    现在看起来不错。如果你的页面只会查询一次信息,那么只要它现在工作就可以了。如果要允许多个查询(例如允许用户选择日期并按按钮检索另一天的信息),则可能需要 empty 之前的相关要素 append 给他们新的东西。

    推荐文章