从2个文本框计算

时间:2019-04-17 14:37:35

标签: javascript html

我想创建2个文本框,当我在第一个文本框中输入总和时,会在第二个文本框中进行查看,但是当我给出代码时,它无法正确运行。

<script>
function addNumbs() {
var n1 = parseInt(document.getElementById("num1").value);
var n2 = parseInt(document.getElementById("num2").value);
var sum = n1 +n2;
document.getElementById("num2").value =sum
if (sum >1000)
    window.alert("Over the limit babe!!")
}
</script>

<body>
<input type="text" value=0 id= num1>
<input type="text" value=0 id= num2>
<button onclick("addNumbs()")>Add</button>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

主要问题是按钮的onclick属性的语法。试试这个:

function addNumbs() {
  var n1 = parseInt(document.getElementById("num1").value);
  var n2 = parseInt(document.getElementById("num2").value);
  console.log(n1, n2);
  var sum = n1 + n2;
  document.getElementById("num2").value = sum;
  if (sum >1000){
    window.alert("Over the limit babe!!");
  }
}
<input type="text" value=0 id= num1>
<input type="text" value=0 id= num2>
<button onclick="addNumbs()">Add</button>

答案 1 :(得分:0)

您在html中设置onclick事件的语法错误,应该是 然后使用+将字符串转换为Number而不是使用parseInt

<button onclick = "addNumbs()">Add</button>

但是我建议您使用现代方式通过addEventListener设置事件。

document.querySelector('#add').addEventListener('click',addNumbs)

function addNumbs() {
    var n1 = +document.getElementById("num1").value;
    var n2 = +document.getElementById("num2").value;
    var sum = n1 +n2;
    document.getElementById("num2").value =sum
    if (sum >1000)
        alert("Over the limit babe!!")
}
<input type="text" value=0 id= num1>
<input type="text" value=0 id= num2>
<button id="add">Add</button>

答案 2 :(得分:0)

我认为这是正确的实现方式

function addNumbs() {
document.getElementById("number2").value = parseInt(document.getElementById("number2").value) + parseInt(document.getElementById("number1").value);
if (parseInt(document.getElementById("number2").value) > 1000)
    window.alert("Over the limit babe!!")
}
<input type="text" value="0" id="number1">
<input type="text" value="0" id="number2">
<button onclick = "addNumbs();">Add</button>

相关问题