2015-11-17 104 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>

如果你有不同的轉換來完成,你可以傳遞作爲參數以及或重命名功能。

相關問題