写这篇博客的原因是我在写js代码校验输入框input的值的时候遇到的一点疑惑,校验代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" id="input"/>
<button onclick="check();">校验</button>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
function check() {
if (!$("#input").val()) {
console.log("值为空,校验不通过");
return;
}
console.log("校验通过");
}
</script>
</html>
当然上面的校验是否为空的代码没毛病,但这时候我产生了一丝疑虑,如果input中什么都没输入,那么校验肯定不会通过,这是毫无疑问的,但是如果输入的是’0’呢?
当然我们也知道如果是number类型的0在js的逻辑判断中肯定是false的,而字符串类型的’0’是true,所以这个问题的关键是$(“#id”).val()的值到底是什么类型的?
测试代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" id="text_input"/>
<input type="number" id="number_input"/>
<select id="select">
<option value="">空串</option>
<option value="0">0</option>
</select>
<button onclick="check();">校验</button>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
function check() {
if ($("#text_input").val()) {
console.log("text " + $("#text_input").val() + " is true");
} else {
console.log("text " + $("#text_input").val() + " is false");
}
if (parseInt($("#text_input").val())) {
console.log("parseInt text " + $("#text_input").val() + " is true");
} else {
console.log("parseInt text " + $("#text_input").val() + " is false");
}
if (parseFloat($("#text_input").val())) {
console.log("parseFloat text " + $("#text_input").val() + " is true");
} else {
console.log("parseFloat text " + $("#text_input").val() + " is false");
}
console.log("----------------------------------------------------");
if ($("#number_input").val()) {
console.log("number " + $("#number_input").val() + " is true");
} else {
console.log("number " + $("#number_input").val() + " is false");
}
if (parseInt($("#number_input").val())) {
console.log("parseInt number " + $("#number_input").val() + " is true");
} else {
console.log("parseInt number " + $("#number_input").val() + " is false");
}
if (parseFloat($("#number_input").val())) {
console.log("parseFloat number " + $("#number_input").val() + " is true");
} else {
console.log("parseFloat number " + $("#number_input").val() + " is false");
}
console.log("----------------------------------------------------");
if ($("#select").val()) {
console.log("select " + $("#select").val() + " is true");
} else {
console.log("select " + $("#select").val() + " is false");
}
if (parseInt($("#select").val())) {
console.log("parseInt select " + $("#select").val() + " is true");
} else {
console.log("parseInt select " + $("#select").val() + " is false");
}
if (parseFloat($("#select").val())) {
console.log("parseFloat select " + $("#select").val() + " is true");
} else {
console.log("parseFloat select " + $("#select").val() + " is false");
}
}
</script>
</html>
运行结果如下:
- 输入空串时
- 输入0时
从上面的测试中我们可以看出,只要是$(“#id”).val()获取值,别管你是input还是select,或者input的类型是text还是number,它的值都是字符串类型的,所以像上面校验代码中写的那样校验是否为空是全面可行的,不用担心输入0时会识别成number类型0来判断,同时也推荐使用上面校验代码中的校验方式。