我对编码比较陌生,我试图从HTML数字输入中获取数值,然后在JavaScript中使用该值。
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Phone Price Calculator</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/phonePrice.css">
</head>
<body>
<!--[if lt IE 7]>
<p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<p>How much money is in your bank account?</p><p>$ <input type="number" id="money" placeholder="ex. 9250.00"></input></p>
<p>How much are you willing to spend on a new phone?</p><p>$ <input type="number" id="newPhone" placeholder="ex. 130.00"></input></p>
<button type="button" id="spendButton">Spend Money!</button>
<p>Tax is 8.25%</p>
<hr>
<p id="total">Total: </p>
<script src="../js/phonePrice.js"></script>
</body>
</html>
- 的JavaScript -
let button = document.querySelector("button");
let money = document.getElementById("money").value;
let newPhone = document.querySelector("#newPhone").value;
let tax = 0.0825;
let total = document.getElementsByName("total");
button.addEventListener("click", function (){
console.log(money);
console.log(newPhone);
});
我的console.log语句都返回一个空字符串。我希望能够将变量设置为用户设置的任何输入,然后在我的函数中使用这些值(数字)。非常感谢任何帮助。
答案 0 :(得分:0)
您在加载脚本时将值分配给money
和newPhone
。
然后用户在字段中键入内容(更改字段中的值,但不更改变量中的值)并单击按钮(即使用之前收集的值时)。
单击按钮时收集值,而不是在加载脚本时收集。