我有一个功能,询问您确定年龄的问题。如果用户输入字符串值或根本没有输入任何内容,我想取消该功能并发出提醒。
到目前为止,这是我的代码:
<button id="btn"> Calculate Age </button>
<p id="para"></p>
document.getElementById("btn").addEventListener("click", ageCalc);
function ageCalc () {
// Calculate year of birth
var year = prompt("What year were you born?");
if (parseInt(year) < 1917) {
return alert("Please enter a valid year");
}
// Calculate month of birth
var month = prompt("Numerically, what month were you born?");
if (parseInt(month) > 12 || parseInt(month) < 1 ) {
return alert("Please enter a valid month!");
}
// Calculate day of birth
var day = prompt("What day were you born?");
if(parseInt(day) > 32 || parseInt(day) < 1) {
return alert("Please enter a valid day!");
}
// Calculate age based on user input
var presentDate = new Date ();
var birthDate = new Date(year,month,day);
var age = (presentDate - birthDate) / 1000 / 60 / 60 / 24 / 365;
return document.getElementById("para").innerHTML = "You are " + Math.floor(age) + " years old.";
}
这里的举动是什么?我假设它将以某种方式调整if语句以检查字符串或空白语句,但我有点丢失。有什么想法吗?
答案 0 :(得分:1)
您可以通过简单添加if检查来排除null / undefined / empty year
值。另外,请始终为parseInt方法添加第二个radix
参数:
var year = prompt("What year were you born?");
if (!year || parseInt(year, 10) < 1917) {
return alert("Please enter a valid year");
}
您可以对month
和day
执行相同操作。
答案 1 :(得分:0)
document.getElementById("btn").addEventListener("click", ageCalc);
function ageCalc () {
// Calculate year of birth
var year = prompt("What year were you born?");
if (parseInt(year) < 1917) {
return alert("Please enter a valid year");
}
else if (year == null)
return;
// Calculate month of birth
var month = prompt("Numerically, what month were you born?");
if (parseInt(month) > 12 || parseInt(month) < 1 ) {
return alert("Please enter a valid month!");
}
else if (month == null)
return;
// Calculate day of birth
var day = prompt("What day were you born?");
if(parseInt(day) > 32 || parseInt(day) < 1) {
return alert("Please enter a valid day!");
}
else if (day == null)
return;
// Calculate age based on user input
var presentDate = new Date ();
var birthDate = new Date(year,month,day);
var age = (presentDate - birthDate) / 1000 / 60 / 60 / 24 / 365;
return document.getElementById("para").innerHTML = "You are " + Math.floor(age) + " years old.";
}
答案 2 :(得分:0)
使用parseInt()
时检查输入是否正确解析,检查其结果是否为NaN
,如下所示:
if( parseInt(month) == NaN ){ alert("invalid input"); return false; }
如果用户键入非int可解析输入,它将停止执行。