通过 getElementsByClassName 获取温度转换为摄氏度替换原始温度
Get temperature by getElementsByClassName convert to celsius replace original temperature
温度是从 xml 中提取的。我需要在页面加载后转换此数字并替换原始数字。
<td class="weathertemperature temperatureplus">26</td>
function convert() {
F = document.getElementsByClassName("weathertemperature").value * 9 / 5 + 32;
document.getElementsByClassName("weathertemperature").value = Math.round(F);
}
convert();
当我调试 alert(F) 时;我得到 NaN
getElementsByClassName
returns 必须按索引访问的元素集合,就像访问数组一样。
因为集合本身没有.value
,在数学运算中使用它时得到NaN
。
如果您只想要第一个,请使用 [0]
获得第一个匹配项,或者只使用 .querySelector
和 CSS 选择器。
function convert() {
var wt = document.querySelector(".weathertemperature");
wt.value = Math.round(wt.value * 9 / 5 + 32);
}
convert();
如果您想对多个进行操作,请像处理任何其他类似数组的集合一样使用循环。
此外,您在 <td>
元素上使用了 .value
。不知道为什么。 .value
属性 主要用于表单控件。您是说 .textContent
吗?
getElementsByClassName
returns 一个 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>
如果您要进行不同的转换,也可以将其作为参数传入或重命名该函数。
温度是从 xml 中提取的。我需要在页面加载后转换此数字并替换原始数字。
<td class="weathertemperature temperatureplus">26</td>
function convert() {
F = document.getElementsByClassName("weathertemperature").value * 9 / 5 + 32;
document.getElementsByClassName("weathertemperature").value = Math.round(F);
}
convert();
当我调试 alert(F) 时;我得到 NaN
getElementsByClassName
returns 必须按索引访问的元素集合,就像访问数组一样。
因为集合本身没有.value
,在数学运算中使用它时得到NaN
。
如果您只想要第一个,请使用 [0]
获得第一个匹配项,或者只使用 .querySelector
和 CSS 选择器。
function convert() {
var wt = document.querySelector(".weathertemperature");
wt.value = Math.round(wt.value * 9 / 5 + 32);
}
convert();
如果您想对多个进行操作,请像处理任何其他类似数组的集合一样使用循环。
此外,您在 <td>
元素上使用了 .value
。不知道为什么。 .value
属性 主要用于表单控件。您是说 .textContent
吗?
getElementsByClassName
returns 一个 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>
如果您要进行不同的转换,也可以将其作为参数传入或重命名该函数。