簡體   English   中英

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

[英]How to insert multiple HTML elements using jQuery

我有一個從 Yahoo! 獲取數據的網頁。 天氣 API。 我正在使用這個查詢 我想使用 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>

我的問題是這樣的:

我是否要這樣做的正確方法? 它有效,但它可能只是解釋器的自動填充(例如省略分號)。 這是正確的,如果不是,我該如何解決? 所有幫助表示贊賞。

目前對我來說看起來不錯。 如果您的頁面只查詢一次信息,那么只要它現在可以工作就可以了。 如果你想允許多個查詢(比如允許用戶選擇一個日期並按下一個按鈕來檢索另一天的信息),你可能需要在向它們append新項目之前empty相關元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM