在此代码中,我想通过单击值按钮来添加值

时间:2017-08-10 06:55:47

标签: javascript

我希望通过以下函数单击每个值按钮来添加值



function sum() {
  var txtFirstNumberValue = document.getElementById('txt1').value;
  var txtSecondNumberValue = document.getElementById('txt2').value;
  var txtThirdNumberValue = document.getElementById('txt3').value;
  var txtFourthNumberValue = document.getElementById('txt4').value;
  var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
  var result = parseInt(txtFirstNumberValue) + parseInt(txtThirdNumberValue);
  var result = parseInt(txtFirstNumberValue) + parseInt(txtFourthNumberValue);
  if (!isNaN(result)) {
    document.getElementById('txt1').value = result;
  }
}
// Here I gave the other two events to add to the text field by the id names

<!-- here I gave the three Value buttons and on click function -->
<input type="text" id="txt1"  value="10" />
<input type="button" id="txt2" value="10" onClick="sum();" />
<input type="button" id="txt3" value="20" onClick="sum();" />
<input type="button" id="txt4" value="30" onClick="sum();" />
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以通过将this.value传递给onClick函数来获取按钮的值,其中this表示元素本身。

function sum(value) {
  document.getElementById('txt1').value = Number(document.getElementById('txt1').value) + Number(value);
}
<input type="text" id="txt1"  value="10" />
<input type="button" id="txt2" value="10" onClick="sum(this.value);" />
<input type="button" id="txt3" value="20" onClick="sum(this.value);" />
<input type="button" id="txt4" value="30" onClick="sum(this.value);" />

答案 1 :(得分:0)

这个javascript会帮助你。

<script>
    function sum(e) {
        var result = parseInt(e.value) + parseInt(document.getElementById('txt1').value);
        if (!isNaN(result)) {
                document.getElementById('txt1').value = result;
            }
    }
</script>