如何从HTML文档中捕获数字输入并将其保存为JS中的数值


<div class = "input">
<b>Weight </b><input type = '' id = 'weight' value = '180'>
</div>
<script>
let weight = document.getElementById('weight');
console.log(weight/2.205);
</script>

输出为NaN。有没有一个解决方案可以将"重量"转换为正确的值?感谢您的时间和耐心。

这里有一个解决方案

let weight = parseInt(document.getElementById('weight').value);
console.log(weight/2.205);
<div class = input>
<b>Weight </b><input type="text" id='weight' value = '180' />
</div>

您引用了错误的变量weight而不是height

document.getElementById('weight')将为您提供元素引用,而不是值。

要获得该值,您需要使用.value属性document.getElementById('weight').value

输入框总是会返回字符串——在进行任何数学运算之前,最好有一个parseInt

如果您想创建一个要求用户输入整数的输入。您使用<input type='number'>

在脚本中,您将变量定义为height,然后在console.log()中将其定义为不存在的weight

当试图提取输入值时,您使用document.getElementById('weight').value而不仅仅是document.getElementById('weight')

<div class = input>
<b>Weight </b><input type = '' id = 'weight' value = '180'>
<script>
let weight = document.getElementById('weight');
console.log(weight.value /2.205);
</script>

您需要从html元素中获取value属性,即

let weight= document.getElementById('weight').value; 

但是你得到的值是字符串,如果你正在做除加法之外的任何类型的数学运算,那么你就很好了,因为javascript会进行类型强制,这意味着它会把字符串改成数字,但如果你需要进行加法,那么只需把高度变量放在number((方法中,它就会把字符串改为数字。

我希望这能回答你的问题

最新更新