[英]How to take multiple inputs from the user in Javascript? How to declare variable for all?
我正在做 JavaScript 膳食營養計算器。 它是一個有 5 行的模板,每行有 4 個輸入,所以總共 20 個,type=value。 每個輸入都有不同的 id。
有什么方法可以同時讀取所有輸入而不重復“var x = document.getElementById('x').value”20 次?
最好的,
<html>
<head>
</head>
<body>
<div>
<h1>Calculator</h1>
<div>ingredient:
<input type="number" id="x" placeholder="x">
<input type="number" id="y" placeholder="y">
<input type="number" id="z" placeholder="z">
<input type="number" id="a" placeholder="a"></div>
<button onclick="calo()" id="cal">Go</button>
<h1>Facts</h1>
</div>
<div id="result">Result is displayed here.</div>
</body>
</html>
function calo() {
const [x,y,z,a] = [...document.querySelectorAll('input')];
document.querySelector("pre").textContent = x.outerHTML + "\n" + y.outerHTML + "\n" + z.outerHTML + "\n" + a.outerHTML;
var calculate = x + y + z + a;
document.getElementById("result").innerHTML = calculate;}
您可以使用document.querySelectorAll
。
document.querySelectorAll('input')
.forEach(input=>console.log("Id:", input.id, "Value:", input.value));
如果要將input
元素聲明為單獨的變量,可以使用解構賦值。 例子:
const [x,y,z] = document.querySelectorAll('input'); document.querySelector("pre").textContent = x.outerHTML + "\n" + y.outerHTML + "\n" + z.outerHTML;
<input type="number" id="x"> <input type="number" id="y"> <input type="number" id="z"> <pre></pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.