简体   繁体   English

如何在JavaScript中对每个循环的选项值求和

[英]How to sum values of options per loop in JavaScript

since I'm a very beginner in JavaScript I've got stuck with a short script. 由于我是JavaScript的初学者,因此我不得不使用简短的脚本。 Here's the deal: I have a formular with 30 Options and each has the values from 1-10. 这是交易:我有一个带30个选项的公式编制器,每个选项的值都在1-10之间。 Now I want to sum them up and show the result while the user is still changing the options. 现在,我想对它们进行总结,并在用户仍在更改选项时显示结果。

function calculate() 
{
    input1 = parseFloat(document.character.input1.value);
    input2 = parseFloat(document.character.input2.value);
    input3 = parseFloat(document.character.input3.value);
    input4 = parseFloat(document.character.input4.value);
    input5 = parseFloat(document.character.input5.value);
    input6 = parseFloat(document.character.input6.value);
    input7 = and so on

    document.getElementById("output").innerHTML = (input1 + input2 + input3 + input4 + input5 + input6 ...).toString();
}

It works, but I wanted to make it way shorter with a for-loop. 它可以工作,但是我想通过for循环使其更短。 But whatever I try, I couldn't get it to work. 但是,无论我如何尝试,我都无法正常工作。 Could anyone help me here? 有人可以在这里帮我吗?

You could try doing something like this: 您可以尝试执行以下操作:

var total = 0;
for ( var i = 1; i <= 30; i++ ){
  total += parseFloat( document.character[ "input" + i ].value );
}
document.getElementById( "output" ).innerHTML = total;

All I am doing here is using the variable i to assemble the key for the character object. 我在这里所做的只是使用变量i来组装字符对象的键。 The value is added (for each iteration) to the total variable which is finally placed in the #output element's content. 该值(每次迭代)被添加到total变量中,该变量最终被放置在#output元素的内容中。

I don't understand how users can "change an option" so as to change the sum of the values of a select element's options. 我不明白用户如何才能“更改选项”以更改选择元素的选项的值总和。 But anyway, you can do it like: 但是无论如何,您可以像这样:

<select onchange="getTotal(this);">

and the function: 和功能:

function getTotal(select) {
  var total = 0;
  var options = select.options;
  for (var i=0, iLen=options.length; i<iLen; i++) {
    total += +options[i].value;
  }
  document.getElementById('output').innerHTML = total;
}

if you have a multiple select and only want to sum those that are selected, then you can do: 如果您有多个选择,并且只想对选择的那些求和,则可以执行以下操作:

  total += options[i].selected? +options[i].value : 0;

Be careful though, change listeners on select elements may behave a little differently in different browsers. 但是请注意,在不同的浏览器中,选择元素上的更改侦听器的行为可能有所不同。

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

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