4 个回答

一竿子买卖……fnum和snum,在程序运行前就取好值了,而并不是onclick时再取值,这就相当于一个常量了,所以怎么算都是(初始值)0.

SCRD
  • 178

值放在点击时取当时的值

var eleFirstNumber = document.getElementById("first-number");
var eleSecondNumber = document.getElementById("second-number");
document.getElementById("add-btn").onclick = function(){
  var fnum = Number(eleFirstNumber.value);
  var snum = Number(eleSecondNumber.value);
  document.getElementById("result").innerHTML =  fnum + snum;
}

应该在 onclick 中获取 input 值,即

document.getElementById("add-btn").onclick = function(){
  var fnum = Number(document.getElementById("first-number").value);
  var snum = Number(document.getElementById("second-number").value);
  document.getElementById("result").innerHTML =  fnum + snum;
}

你的代码里 fnum 和 snum 始终是 input 的初始值 0

Rossy1
  • 2.1k

先取得值,没有在点击事件时取值


document.getElementById("add-btn").onclick = function(){
  var fnum = Number(document.getElementById("first-number").value);
  var snum = Number(document.getElementById("second-number").value);
  document.getElementById("result").innerHTML =  fnum + snum;
}
宣传栏