如何处理来自文本框的输入以不打印 NaN
Posted
技术标签:
【中文标题】如何处理来自文本框的输入以不打印 NaN【英文标题】:How to handle input from a textbox to not print a NaN 【发布时间】:2022-01-14 20:31:21 【问题描述】:我正在尝试从文本框中获取用户输入,然后单击旁边的按钮以计算圆的面积。问题是 alert 总是打印 NaN。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="./css/style.css">
<script>
const PI = 3.14159;
function getAreaOfCircle(rad)
let area = PI * Math.pow(rad, 2);
alert(area);
</script>
</head>
<body>
<input type="text" placeholder="Type something..." id="myInput">
<input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle">
</body>
</html>
【问题讨论】:
【参考方案1】:你必须在你的函数上传递输入值。当您将代码作为参数/参数传递给您的函数时。所以你可以这样编码:
<input type="button" onclick="getAreaOfCircle(document.getElementById('myInput').value);" value="Calculate Area of a Circle">
【讨论】:
【参考方案2】:您需要获取实际的输入文本并将其值转换为浮点数:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="./css/style.css">
<script>
const PI = 3.14159;
function getAreaOfCircle()
//Get the radius from the input field
let rad = document.getElementById("myInput").value;
//Check if the input is not empty, if it is set rad to 0
rad = rad !== "" ? parseFloat(rad) : 0;
let area = PI * Math.pow(rad, 2);
alert(area.toFixed(2));
</script>
</head>
<body>
<input type="text" placeholder="Enter the circle radius" id="myInput">
<input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle">
</body>
</html>
【讨论】:
【参考方案3】:你没有在函数getAreaOfCircle
中传递rad
所以你可以在函数getAreaOfCircle
中获取值:
const rad = document.querySelector("#myInput").value;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="./css/style.css">
<script>
const PI = 3.14159;
function getAreaOfCircle()
const rad = document.querySelector("#myInput").value;
let area = PI * Math.pow(rad, 2);
alert(area);
</script>
</head>
<body>
<input type="text" placeholder="Type something..." id="myInput">
<input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle">
</body>
</html>
【讨论】:
以上是关于如何处理来自文本框的输入以不打印 NaN的主要内容,如果未能解决你的问题,请参考以下文章