我使用 document.getElementById.innerHTML 获取 HTML 元素的值,然后将该值传递给返回该值类型的函数。然后,我使用 if/else if block 将值的类型打印到控制台。我的问题是 typeof 方法总是返回字符串类型。如果我不使用 document.getElementById 并直接声明变量,则 typeof 返回正确的类型。感谢您的帮助!
JS fiddle 在这里:http://jsfiddle.net/sY7uW/
// get innerhtml of div
var LowTemperature = document.getElementById('LowTemperature').innerHTML;
// check type from function return
if(check_type(LowTemperature) === 'number') {
console.log(LowTemperature + " is a number");
}
else if(check_type(LowTemperature) === 'string') {
console.log(LowTemperature + " is a string");
}
// return var type
function check_type(value) {
return typeof value;
}
最佳答案
innerHTML 只会返回一个字符串。您需要将其解析为整数。
关于javascript - 从 document.getElementById 返回的 HTML 元素类型 String not Number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940513/