2015-11-17 39 views
0

温度从xml中拉入。我需要在页面加载后转换此数字并替换原始数字。通过getElementsByClassName获取温度转换为摄氏温度取代原始温度

<td class="weathertemperature temperatureplus">26</td> 

function convert() { 
     F = document.getElementsByClassName("weathertemperature").value * 9/5 + 32; 
    document.getElementsByClassName("weathertemperature").value = Math.round(F); 

} 
convert(); 

当我调试警报(F);我得到NaN

回答

0

getElementsByClassName返回您必须通过索引访问的元素集合,就像您使用数组一样。

因为集合本身没有.value,所以在数学运算中使用它时会得到NaN

如果您只想要第一个匹配项,请使用[0]获取第一个匹配项,或者仅使用带有CSS选择器的.querySelector

function convert() { 
    var wt = document.querySelector(".weathertemperature"); 
    wt.value = Math.round(wt.value * 9/5 + 32); 
} 
convert(); 

如果您想对多个进行操作,请像使用任何其他类似数组的收集一样使用循环。

另外,您在<td>元素上使用.value。不知道为什么。 .value属性主要用于表单控件。你的意思是.textContent

+0

.textContent工作得好多了,谢谢! – user2882684

0

getElementsByClassName返回一个NodeList,所以你必须循环它们来为它们设置新的温度。

您可以将元素集合传递给函数并在其中循环。

function convert(items) { 
 
    for (var i = 0, len = items.length; i < len; i++) { 
 
    items[i].innerText = Math.round(items[i].innerText * 9/5 + 32); 
 
    } 
 
} 
 

 
convert(document.getElementsByClassName("weathertemperature"));
<table> 
 
    <tbody> 
 
    <tr> 
 
     <td class="weathertemperature temperatureplus">26</td> 
 
     <td>27</td> 
 
     <td class="weathertemperature temperatureplus">28</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

如果你有不同的转换来完成,你可以传递作为参数以及或重命名功能。

相关问题