javascript - 从输入中获取用户输入(数字)
问题描述
我正在尝试为我正在从事的项目制作价格计算器。用户应该选择他们想要的门票类型和数量。然后程序计算出总成本。
我在 JavaScript 中设置了门票价格。问题是我的代码没有识别出它是来自 HTML 输入元素的数字输入,因此它NaN
作为总成本输出。我猜我的功能是错误的。
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<h1>Museum Ticket Pricing Application</h1>
<label for="adults" id="adults">Number of Adults: </label>
<input type="number" id="adults">
<br>
<br>
<label for="children" >Number of Children: </label>
<input type="number" id="children">
<br>
<br>
<label for="under7" >Number of children under 7: </label>
<input type="number" id="childrenUnder7">
<br>
<br>
<label for="senior" >Number of Seniors: </label>
<input type="number" id="senior">
<br>
<Button id="totalBtn">Total Price</Button>
<p></p>
<script src="app.js" async defer></script>
</body>
</html>
Javascript:
let adults = document.getElementById("adults");
let children = document.getElementById("children");
let under7 = document.getElementById("childrenUnder7");
let senior = document.getElementById("senior");
const totalBtn = document.querySelector("button");
const para = document.querySelector("p");
let adultFee = 10;
let childrenFee = 5;
let under7Fee = 2;
let seniorFee = 7;
totalBtn.addEventListener("click", function totalPrice() {
let adultsInput = adults.value;
let childrenInput = children.value;
let under7Input = under7.value;
let seniorInput = senior.value;
let totalcalculation = adultsInput * adultFee + childrenInput * childrenFee + under7Input * under7Fee + seniorInput * seniorFee;
totalcalculation;
para.textContent = "the total price is " + totalcalculation;
});
解决方案
问题在这里:
<label for="adults" id="adults">Number of Adults: </label>
<input type="number" id="adults">
你已经复制id="adults"
了,所以let adults = document.getElementById("adults");
实际上是重新调整你的标签而不是输入。只需从中删除id="adults"
,<label for="adults" id="adults">Number of Adults: </label>
它应该可以正常工作。
推荐阅读
- c# - 子类看不到父方法
- javascript - 按 ID 获取元素不起作用 | JavaScript
- javascript - 这是使用 requestAnimationFrame 的正确方法吗?
- reactjs - Snackbar 在清除前显示空消息
- python - 在python中使用round函数
- python - 为什么我的 while 不使用两个条件循环仅使用第一个条件而忽略第二个条件?
- python - 如何使用参数扩展 docker 容器
- java - 序列化过程不断地覆盖自己?
- javascript - discord.js - 命令正在添加更多要嵌入的字段
- javascript - (节点:9374)警告:要加载 ES 模块,请设置“类型”:“模块”