我有一个页面,根据画布上的字符串显示gif图标。例如“晴天”。可以从api获取该字符串。我的问题是如何将包含该字符串的变量“icon”分配给我的画布的id。当然,有更好的方法可以做到这一点,因为我是初学者。
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Animated weather icons</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<figure class="icons">
<canvas class="weatherIcon" width="64" height="64"></canvas>
</figure>
<script src="https://rawgithub.com/darkskyapp/skycons/master/skycons.js"></script>
<script>
$(document).ready(function weather(){
$.getJSON("https://api.darksky.net/forecast/[key]/59.868098,%2017.678976?lang=sv&callback=?",
function(json) {
var weatherJSON = json.currently;
var icon=weatherJSON.icon;
var icons = new Skycons({"color": "white"});
icons.set("clear-day", Skycons.CLEAR_DAY);
icons.set("clear-night", Skycons.CLEAR_NIGHT);
icons.set("partly-cloudy-day", Skycons.PARTLY_CLOUDY_DAY);
icons.set("partly-cloudy-night", Skycons.PARTLY_CLOUDY_NIGHT);
icons.set("cloudy", Skycons.CLOUDY);
icons.set("rain", Skycons.RAIN);
icons.set("sleet", Skycons.SLEET);
icons.set("snow", Skycons.SNOW);
icons.set("wind", Skycons.WIND);
icons.set("fog", Skycons.FOG);
var iconWeather = document.getElementsByClassName("weatherIcon");
iconWeather.id = icon;
icons.play();
});
});
</script>
</body>
</html>
答案 0 :(得分:0)
尝试:
document.getElementsByTagName("canvas")[0].setAttribute("id", icon);
答案 1 :(得分:0)
要达到预期效果,请使用以下选项
Document.getElementByClassName返回具有所有给定类名的所有子元素的类数组对象。
更改iconWeather.id = icon; to iconWeather [0] .setAttribute(“id”,icon);