我想运行一个函数来检查用户输入的年龄是否足以让他投票。我用两种方式做到了
这两个代码都运行良好,并且都以相同的方式工作。我想知道这两种方法是否存在任何性能差异,以及应使用哪种方法来执行此类操作。
第一种方式 :
function validateAge() {
var age = document.getElementById("age").value;
var paragraph = document.getElementById("result");
if (age == "") {
paragraph.innerHTML = "Please enter your age";
} else if (age < 18) {
paragraph.innerHTML = "You are too young to vote";
} else {
paragraph.innerHTML = "You are eligible to vote";
}
}
<title>Age validator</title>
<h1>Enter your age to check if you are eligible to vote : </h1>
<label>Enter Your age : </label>
<input type="text" id="age" /><br/>
<input type="button" onclick="validateAge()" value="Validate" /><br/>
<p id="result"></p>
第二种方式 :
function validateAge() {
try {
var agge = document.getElementById("age").value;
if (agge == "") {
throw "Please enter your age";
} else if (agge < 18) {
throw "You are too young to vote";
} else {
throw "You are eligible to vote";
}
} catch (obj) {
document.getElementById("result").innerHTML = obj;
}
}
<title>Age validator</title>
<h1>Enter your age to check if you are eligible to vote : </h1>
<label>Enter Your age : </label>
<input type="text" id="age" /><br/>
<input type="button" onclick="validateAge()" value="Validate" /><br/>
<p id="result"></p>
慕森王
动漫人物
繁花不似锦
相关分类