Skycons,不能两次显示相同的图标?

时间:2014-07-04 10:19:57

标签: javascript css

我已将JavaScript插件“Skycons”连接到雅虎天气RSS源。我遇到的问题是多天可能有相同的天气预报,因为插件从ID而不是类中拉出图标我无法再次拉出相同的图标。

例如,下面的所有图标都会显示最后一个li实例 - 因为我重复了id雪:

<ul class="days">
       <li class="col-md-3 col-sm-3 col-xs-3"><strong>Saturday</strong>
             <canvas id="snow" width="50" height="50"></canvas>
             <span>19&deg;</span>
       </li>
       <li class="col-md-3 col-sm-3 col-xs-3"><strong>Sunday</strong>
             <canvas id="rain" width="50" height="50"></canvas>
             <span>19&deg;</span>
       </li>
       <li class="col-md-3 col-sm-3 col-xs-3"><strong>Monday</strong>
             <canvas id="sleet" width="50" height="50"></canvas>
             <span>19&deg;</span>
       </li>
       <li class="col-md-3 col-sm-3 col-xs-3"><strong>Wednesday</strong>
             <canvas id="snow" width="50" height="50"></canvas>
             <span>19&deg;</span>
       </li>
</ul>

这是我的初学JS:

<!--SkyCons-->  
<script type="text/javascript" src="js/vendors/skycons/skycons.js"></script> 
<script>
      var icons = new Skycons({"color": "#fff"}),
          list  = [
            "clear-day", "clear-night", "partly-cloudy-day",
            "partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind",
            "fog"
          ],
          i;

      for(i = list.length; i--; )
        icons.set(list[i], list[i]);

      icons.play();
    </script> 

这里是引用的JS文件的链接:

https://github.com/darkskyapp/skycons/blob/master/skycons.js

1 个答案:

答案 0 :(得分:10)

您应该使用适用于元素引用的版本而不是id

并将html更改为使用类而不是ID

for(i = list.length; i--; ) {
    var weatherType = list[i],
        elements = document.getElementsByClassName( weatherType );
    for (e = elements.length; e--;){
        icons.set( elements[e], weatherType );
    }
}

并将您的HTML更改为

   <li class="col-md-3 col-sm-3 col-xs-3"><strong>Saturday</strong>
         <canvas class="snow" width="50" height="50"></canvas>
         <span>19&deg;</span>
   </li>
   <li class="col-md-3 col-sm-3 col-xs-3"><strong>Sunday</strong>
         <canvas class="rain" width="50" height="50"></canvas>
         <span>19&deg;</span>
   </li>
   <li class="col-md-3 col-sm-3 col-xs-3"><strong>Monday</strong>
         <canvas class="sleet" width="50" height="50"></canvas>
         <span>19&deg;</span>
   </li>
   <li class="col-md-3 col-sm-3 col-xs-3"><strong>Wednesday</strong>
         <canvas class="snow" width="50" height="50"></canvas>
         <span>19&deg;</span>
   </li>

如果您需要支持IE8及更早版本,则需要将此polyfill用于getElementsByClassName函数:Polyfill for getElementsByClassName for particular uses