2017-04-22 99 views
0

我有一个基于画布上的字符串显示gif图标的页面。例如“晴天”。可以从api获取该字符串。我的问题是我如何将包含该字符串的变量“图标”分配给我的画布的ID。当然,因为我是初学者,所以有更好的方法来做到这一点。如何更改画布上的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

你将不得不澄清你想要的。 “将包含该字符串的变量”图标“分配给我的画布ID”是否要将画布元素的'id'设置为对象的属性'icon.id'?或将'canvas.id'设置为对象'icon'? (不能这样做,因为'id'只能保存字符串)或者其他的东西? – Blindman67

回答

0

尝试:

document.getElementsByTagName("canvas")[0].setAttribute("id", icon); 
0

为了达到预期的结果,请使用以下选项

Document.getElementByClassName返回具有所有给定的类名称的所有子元素的数组状物体。

更改iconWeather.id =图标; to iconWeather [0] .setAttribute(“id”,icon);

+0

创建codepen网址以供参考 - https://codepen.io/nagasai/pen/ybJPpy –