首页 > 解决方案 > 根据用户输入显示最多 12 个时间表

问题描述

当我控制台记录它说“”的变量时,似乎认为 ttinput 是一个字符串。其他一切似乎都在工作我只是不知道如何将 ttinput 作为数字。

document.getElementById("enter").addEventListener("click", ttcalc)
var ttinput = document.getElementById("table").value;
var ttoutput;


function ttcalc(){

        var display = "";

        for(var i = 1; i <= 12; i++){

            ttoutput = ttinput * i;
            display += ttinput + "*" + i + "=" + ttoutput + "<br>"
            console.log(ttoutput, ttinput, i);

        }

    document.getElementById("output").innerHTML = display;

}

这是我的html

    <form>
            <h1>Enter what times table you wish to see</h1>
            <input type="number" id="table"><br>
        </form>

        <button id="enter">Show Times Table</button>
    </div>

标签: javascripthtmlfor-loop

解决方案


问题是价值

var ttinput = document.getElementById("table").value;

在页面加载时读取(当输入字段为空时)。如果您在函数中移动该行代码,它将在单击按钮后读取输入字段的值。


如果您想确保输入的值是一个数字,您可以使用该parseInt()函数,然后使用如下函数检查结果是否是一个数字isNaN()

var ttinput = parseInt(document.getElementById("table").value);

然后使用isNaN()

if( !isNaN(ttinput) ) {
    // ttinput is a number
} else {
    // ttinput is not a number
}

更多:parseIntisNaN


检查以下示例:

document.getElementById("enter").addEventListener("click", ttcalc)

function ttcalc() {
  var ttinput = parseInt(document.getElementById("table").value);
  var ttoutput;
  var display = "";

  if( !isNaN(ttinput) ) {
    for(var i = 1; i <= 12; i++) {
      ttoutput = ttinput * i;
      display += ttinput + "*" + i + "=" + ttoutput + "<br>"
      console.log(ttoutput, ttinput, i);
    }
    document.getElementById("output").innerHTML = display;
  } else {
    console.log("value is not a number");
  }
}
<button id="enter">Enter</button>
<input type="text" id="table" value="">
<div id="output"></div>


推荐阅读