将输入字段与字符中的商店编号相加

时间:2018-02-13 17:20:00

标签: javascript

我需要对输入字段求和,难的是我需要将a=1 b=2 c=3存储到z,这样每个字符都会有数字。输入字段的字符类似于a,并将a的数量与5相加并显示新字符。

我尝试使用此代码,但我无法在号码中存储数字:

<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<script type="text/javascript">
    function doMath()
    {
        var my_input1 = document.getElementById('my_input1').value;
        var my_input2 = document.getElementById('my_input2').value;
        var sum = parseInt(my_input1) + parseInt(my_input2);
        document.write(sum);
    }
</script>

2 个答案:

答案 0 :(得分:0)

您可以使用charCodeAt获取字母的字符代码:

'a'.charCodeAt(0)  // 97

如果要为每个字符定义一个自定义数字,则必须声明一个对象,如:

let values = { a: 1, b: 2, c: 3 }
values.a // 1

答案 1 :(得分:0)

function doMath() {
  var charMap = {
    a: 1,
    b: 2,
    c: 3,
    d: 4
  }; //add more as needed
  // note I make NO attempt to ensure the entered value exists here.
  var my_input1 = document.getElementById('my_input1').value;
  var my_input2 = document.getElementById('my_input2').value;
  console.log(charMap[my_input1], charMap[my_input2]);
  var sum = charMap[my_input1] + charMap[my_input2];
  document.getElementById('showresult').innerHTML = sum;
}
<input type="text" id="my_input1" />
<input type="text" id="my_input2" />
<input type="button" value="Add Them Together" onclick="doMath();" />
<div id="showresult"></div>

相关问题