javascript - 变化的输出标准值?

标签 javascript html

我有 1 个输入。我想要做的是 input = "5"然后把 "3"放在 "total"和 "4"放在 "total2"。对于输入的每个 +1,对“total”和“total2”执行 +1。 低于 5 的任何值都没有关系,因为如果低于 5,我的输出 div 将不会显示。

简而言之:“当我给出 5 的输入时,我得到 4 和 5 的输出,但我需要 3 和 4。之后输入的每个 +1 我需要输出的 +1。”

这是我目前所拥有的:

function updateTotal() {
  var total = 0; //
  var total2 = 0; //
  var list = document.getElementsByClassName("input");
  var values = [];
  for (var i = 0; i < list.length; ++i) {
    values.push(parseFloat(list[i].value));
  }
  total = values.reduce(function(previousValue, currentValue, index, array) {
    return previousValue + currentValue;
  });
  document.getElementById("total").value = total;
  document.getElementById("total2").value = total - 1;
}
<input type="text" class='input' value="0" onchange='updateTotal();'>
<br>
<br>
<br>
<input name="total" type="text" id="total" value="">
<input name="total2" type="text" id="total2" value="">

但我似乎无法弄清楚如何给它一个标准值 3 和 4。

最佳答案

我不明白那些 for-loopreduce与只有一个问题相关<input class='input'>但是好吧...

我想做的是输入 = "5",然后将 "3"放在 "total"上,将 "4"放在 "total2"上。

换句话说,您需要两个输入分别为第一个输入值的 -1 和 -2。

function updateTotal() {
  // var total = 0; I don't know
  // var total2 = 0; why you wrote those

  // I assume you have multiple <input class="input"> 
  const list = document.getElementsByClassName("input");
  const values = [];
  for (let i = 0; i < list.length; ++i) {
    values.push(parseFloat(list[i].value));
  }
  //and here you accumulate all those values
  let total = values.reduce(function(previousValue, currentValue) {
    return previousValue + currentValue;
  });


  // but code relevant to the problem is DOWN HERE

  // here you assigned INPUT value to TOTAL (eg input==5)
  // document.getElementById("total").value = total; but you need 2 less
  document.getElementById("total").value = total - 2;

  // here you assigned INPUT-1 value to TOTAL (eg input=4)
  // all ok here
  document.getElementById("total2").value = total - 1;
}
<input type="text" class='input' value="0" onchange='updateTotal();' placeholder="input">
<br>
<br>
<br>
<input name="total" type="text" id="total" placeholder="total">
<input name="total2" type="text" id="total2" placeholder="total 2">

关于javascript - 变化的输出标准值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657449/

相关文章:

javascript - React 电子邮件验证中的正则表达式

html - maxlength 和 minlength 不验证 IE 中的 HTML 文本框

html - 为什么我不能用定位移动我的一些 table ?

javascript - 倒数计时器不会因clearInterval()而停止

javascript - 如何将类从多个类为 "abcd+n"的div添加到另一个类为 "qwer+n"的div

javascript - Json.stringify() 和不使用 stringify 有什么用

html - 粘性页脚无法与侧边栏一起正常工作

JavaScript 图像路径正斜杠已删除

javascript - 动态创建 Angular View

javascript - Keypress 在带有 div 的表格中不起作用?