我有 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-loop
和 reduce
与只有一个问题相关<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/