【问题标题】:How to take multiple inputs from the user in Javascript? How to declare variable for all?如何在Javascript中从用户那里获取多个输入?如何为所有人声明变量?
【发布时间】:2020-06-24 20:38:34
【问题描述】:

我正在做 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;}

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用document.querySelectorAll

    document.querySelectorAll('input')
        .forEach(input=>console.log("Id:", input.id, "Value:", input.value));
    

    如果您希望将input 元素声明为单独的变量,您可以使用destructuring assignment。示例:

    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>

    【讨论】:

    • 3 个输入的“type=name”的样子: document.querySelectorAll('input').forEach(input=>console.log("Name:", input.id, "Value:", input.value)) ;我试过这样,但 x,y 和 z 没有声明
    • @Pawel 未声明是什么意思? document.querySelectorAll 只是获取所有 input 元素的集合,您可以循环访问这些元素。
    • @Pawel 我还更新了我的答案以提供一些额外的指导。
    • 我很想收集所有 4 个输入并在显示结果后采取行动。试图了解它是如何工作的。感谢您的帮助
    • @Pawel 没问题。您还有什么需要帮助的吗?
    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2021-05-24
    相关资源
    最近更新 更多