我正在制作一些按钮,我希望它们有一些整数值。当我单击按钮时,我希望它们在下方的文本框中显示值。一旦我单击第二个按钮,它的值应该添加到第一个按钮一次并显示在文本框中。所有按钮都应该如此。所以基本上它是一种计算器,但我不想有一个单独的+号,我只想单击按钮并添加它们的值并显示在文本框中。
这是我尝试使用的 JavaScript。
var m1;
var m2;
var m3;
var m4;
var m5;
var m6;
function f1(){
m1=1;
}
function f2(){
m2=5;
}
function f3(){
m3=10;
}
function f4(){
m4=20
}
function f5(){
m5=50;
}
function f6(){
m6=100;
}
function ff(){
document.getElementById("total").value=m1+m2+m3+m4+m5+m6;}
我将所有这些功能添加到关联的按钮(1,5,10,20,50 是我想要关联到按钮的值)。 按钮和文本字段如下:
<input type="button" id="1" onclick="f1(); ff();">
<input type="button" id="2" onclick="f2(); ff();">
<input type="button" id="3" onclick="f3(); ff();">
<input type="button" id="4" onclick="f4(); ff();">
<input type="button" id="5" onclick="f5(); ff();">
<input type="button" id="6" onclick="f6(); ff();">
<input type="text" id="total"">
最佳答案
将单击的按钮的值作为参数传递并将其添加到总和中。
我正在添加重置按钮,以防您想重置总和。
var sum = 0;
function f(val){
sum += val;
document.getElementById("total").value = sum;
}
function reset(){
sum = 0;
document.getElementById("total").value = sum;
}
<input type="button" value = "1" id="1" onclick="f(1);;">
<input type="button" value = "5" id="2" onclick="f(5); ">
<input type="button" value = "10" id="3" onclick="f(10);">
<input type="button" value = "20" id="4" onclick="f(20); ">
<input type="button" value = "50" id="5" onclick="f(50);">
<input type="button" value = "100" id="6" onclick="f(100);">
<input type="text" id="total"">
<button onclick="reset()" >Reset</button>
关于javascript - 单独点击按钮时如何添加按钮的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919743/