【发布时间】:2018-04-23 00:05:10
【问题描述】:
function bereken() {
input1 = document.getElementById('input1').value;
input2 = document.getElementById('input2').value;
input1Valid = Number.isInteger(document.getElementById('input1'));
input2Valid = Number.isInteger(document.getElementById('input2'));
if (Number.isInteger(input1) && Number.isInteger(input2)) {
alert('De getallen zijn allebei hele getallen')
}
}
<!DOCTYPE html>
<html>
<head>
<script src='code.js'></script>
</head>
<body>
<center>
<h1>GGD calculator</h1>
<p>Reken de Grote Gemene Deler uit van <input type='number' id='input1'> en <input type='number' id='input2'>.</p>
<br>
<input type='button' value='Bereken!' onClick='bereken()'>
</center>
</body>
</html>
我在练习 JavaScript 时遇到了这个问题,有人可以帮助我吗?
我希望它在输入的两个数字都是整数时提醒我的消息,为什么这不起作用?
【问题讨论】:
-
请记住,HTML 中的“T”代表“文本”。 HTML 中只有一种数据类型——字符串。您从 HTML 中提取的任何值都将始终是一个字符串。
-
您需要先将字符串转换为数字。使用
parseInt(value, 10)将其转换为数字。然后,您可以检查返回值是否为非浮点整数。 -
@ssc-hrep3 你也可以把
+直接放在字符串前面,把它转换成数字。
标签: javascript html web