简体   繁体   English

如何使用 for 循环对用户插入的数字求和?

[英]How to use for loop to sum a numbers inserted by the user?

i'm trying to create a simple project where the user is prompted to enter how many numbers he would like to add(sum).我正在尝试创建一个简单的项目,提示用户输入他想添加多少个数字(总和)。 then when he click the button, a javascript will create a number of input tags equal to the number he inserted and then he will fill them with a number and click another button to calculate the result of the summation and here is the problem.然后当他单击按钮时,javascript 将创建多个与他插入的数字相等的输入标签,然后他将用一个数字填充它们并单击另一个按钮来计算求和的结果,这就是问题所在。 below is a simplified snippet explain what is the problem:下面是一个简化的片段,解释了问题所在:

function CL(){
        const items = document.getElementById("items");
        for (var i = 1; i < 3; i++) {
              const inpt = document.createElement("input");
              inpt.setAttribute("type","text");
              inpt.setAttribute("style","margin:5px;");
              inpt.setAttribute("id","y"+i);
              inpt.setAttribute("value","");
              const newline = document.createElement("br");
              items.appendChild(inpt);
              items.appendChild(newline);
            }
    }

    function Add(){
        const y = 0;
        const sum = 0;
        var is;
        for (var i = 1; i < 3; i++) {
            is = i.toString();
         y = Number(document.getElementById('y'+ is).value);
         sum = sum + y;
    }
        document.getElementById("demo").innerHTML = sum;
    }

in the for loop how can i use getElementById with variables id like item1,item2,item3,...,itemN??在 for 循环中,我如何将 getElementById 与变量 id (如 item1、item2、item3、...、itemN)一起使用? is there other way to achieve what i want?还有其他方法可以实现我想要的吗?

You can take all items with ID "y" + consecutive number prefix on this way document.getElementById('y' + i).value;您可以通过这种方式获取ID为“y”+连续数字前缀的所有项目document.getElementById('y' + i).value;

Do not use "Add" for function name and Functions do not have to start with capital letters!不要对 function 名称使用“添加”,函数不必以大写字母开头!

 calckStart(); function calckStart() { const items = document.getElementById("items"); for (var i = 1; i < 3; i++) { const inpt = document.createElement("input"); inpt.setAttribute("type", "text"); inpt.setAttribute("style", "margin:5px;"); inpt.setAttribute("id", "y" + i); inpt.setAttribute("value", ""); const newline = document.createElement("br"); items.appendChild(inpt); items.appendChild(newline); } var button = document.createElement('button'); button.innerHTML = 'ClickMe' items.appendChild(button); button.addEventListener('click', calculateVal); } function calculateVal() { var res = 0; for (var i = 1; i < 3; i++) { res = res + +document.getElementById('y' + i).value; } var items = document.getElementById("items"); var result = document.createElement('div'); result.innerHTML = res; items.appendChild(result); }
 <div id="items"></div>

A better way is...更好的方法是...

When you create elements, you can assign them a CLASS attribute that is one for all input elements.创建元素时,可以为它们分配一个 CLASS 属性,该属性是所有输入元素的一个属性。 You can then take the values from all elements with this class.然后,您可以使用此 class 从所有元素中获取值。

Example:例子:

 calckStart(); function calckStart() { const items = document.getElementById("items"); for (var i = 1; i < 3; i++) { const inpt = document.createElement("input"); inpt.setAttribute("type", "text"); inpt.setAttribute("style", "margin:5px;"); // inpt.setAttribute("id", "y" + i); inpt.setAttribute("value", ""); inpt.setAttribute("class", "numbers"); //<-- Set class const newline = document.createElement("br"); items.appendChild(inpt); items.appendChild(newline); } var button = document.createElement('button'); button.innerHTML = 'ClickMe' items.appendChild(button); button.addEventListener('click', calculateVal); } function calculateVal() { var list = document.getElementsByClassName('numbers'); //<-- Get by class var res = 0; for (var i = 0; i < list.length; i++) { res = res + +list[i].value; } var items = document.getElementById("items"); var result = document.createElement('div'); result.innerHTML = res; items.appendChild(result); }
 <div id="items"></div>

You can use ...args to collect arguments and use .reduce to add the arguments together.您可以使用...args收集 arguments 并使用.reduce将 arguments 添加在一起。

 const items = document.getElementById("items"); for (var i = 0; i < 3; i++) { var inpt = document.createElement("input"); inpt.setAttribute("type","number"); //replaced with number inpt.setAttribute("style","margin:5px;"); inpt.setAttribute("id","y"+i); inpt.setAttribute("value",""); var newline = document.createElement("br"); items.appendChild(inpt); items.appendChild(newline); //added newline appending } function sum(...args) { return args.reduce((a, b) => a+b); //reduce arguments }
 <div id="items"></div><br /><button onclick="document.getElementById('answer').textContent = 'answer: ' + sum(+y0.value, +y1.value, +y2.value)">Add</button><div id="answer"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM