我正在做一个简单的天气应用程序。正如您从下面的代码中看到的那样,我显示了5天的预测,我希望显示为列表,但是有一个问题是我无法将图像附加到我的列表元素中。
我的js文件
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var t = document.createTextNode("Date: " + forecast[i].date.toString().substring(8, 10)
+ "/" + forecast[i].date.toString().substring(5, 7) + " "
+ "Current Temperature: " + forecast[i].temperature.toString() + " "
+ "Maximum: " + forecast[i].temperature_max.toString() + " "
+ "Minimum: " + forecast[i].temperature_min.toString() + " "
+ "Description: " + forecast[i].text.toString() + " ");
li.appendChild(t);
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = "";
我的Html文件
<div id="myDIV" class="header">
<h2 style="margin:5px">Weather Application</h2>
<p id="title">You can search here.</p>
<input type="text" id="myInput" placeholder="Search...">
<span onclick="gettingJSON()" class="addBtn">Add</span>
</div>
<ul id="myUL">
</ul>
答案 0 :(得分:2)
以下是您所缺少的内容:
1:0:d=2016080100:REFC:entire atmosphere:anl
2:415003:d=2016080100:RETOP:cloud top:anl
如果您想在文本之前添加图像,则应首先将其附加。
答案 1 :(得分:2)
您需要创建一个图片元素,将其src
设置为网址,然后将其附加到li
。
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var img = li.appendChild(document.createElement('img'));
img.src = iconurl;
var t = // ...
答案 2 :(得分:1)
你根本没有使用过这个变量iconurl
您可以将Image元素创建为
for (var i = 0; i < 5; i++) {
var li = document.createElement("li");
var iconurl = "https://openweathermap.org/img/w/" + forecast[i].image.toString() + ".png";
var t = document.createTextNode("Date: " + forecast[i].date.toString().substring(8, 10) + "/" + forecast[i].date.toString().substring(5, 7) + " " + "Current Temperature: " + forecast[i].temperature.toString() + " " + "Maximum: " + forecast[i].temperature_max.toString() + " " + "Minimum: " + forecast[i].temperature_min.toString() + " " + "Description: " + forecast[i].text.toString() + " ");
var img = document.createElement("img");
img.src=iconurl;
img.width=20;
img.height=20;
li.appendChild(t);
li.appendChild(img); document.getElementById("myUL").appendChild(li); document.getElementById("myInput").value = "";