示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>表单内容提交</title>
<style>
.error{
color: #bd342d;
}
</style>
</head>
<body>
<form action="s5_new.html" method="get">
<div><input name="姓名" type="text"></div>
<div><input name="学号" type="text"></div>
<div><input name="班级" type="text"></div>
<div><input type="submit"></div>
</form>
<script src="jquery-1.12.4.js"></script>
<script>
$('[type="submit"]').click(function () {
var permit = true;
// 默认是允许提交的
$('.error').remove();
// 必须首先进行添加元素的清空
$('[type="text"]').each(function () {
var val = $(this).val();
console.log(val);
if (val.length<=0){
permit = false;
var prompt = $(this).attr('name');
var tag =document.createElement('span');
tag.className="error";
tag.innerHTML=prompt+"必填";
$(this).after(tag);
return false;
// 结束的只是内循环而已
}
});
return permit;
});
</script>
</body>
</html>