javascript - 根据用户输入显示最多 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>
解决方案
问题是价值
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
}
检查以下示例:
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>
推荐阅读
- python - 使用 Python 使用 ADB 列出文件
- c# - 我的 XAML 中有两个自定义控件,如何将其中一个控件绑定到另一个控件?
- eiffel - eiffel: semantic of ANY default
- .net - 如何根据 Service Fabric 中的取消令牌停止 Topshelf 服务?
- java - 一个接一个地执行 Selenium 测试,而无需通过 testng 重新启动浏览器
- c# - ABP 框架 - ValidateModel() 并显示成功消息的最佳方式
- android - Firebase 云消息传递:新登录用户的新令牌
- python - 来自python字符串的C char数组
- python - 当条目过满/太长时,file.write CSV 中不需要的换行符
- php - 使用 API 获取数据时,HTML 代码未在 PHP 中解析。任何想法为什么会发生这种情况?