<html> <head> <script type="text/javascript" src="./jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#b01").click(function(){ var age= GetAge($("#idCard").val()); $("#age").val(age); var birthDay= GetBirthDay($("#idCard").val()); $("#birthDay").val(birthDay); }); }); //根据身份证号码获取年龄 function GetAge(identityCard) { var len = (identityCard + "").length; if (len == 0) { return 0; } else { if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法 { return 0; } } var strBirthday = ""; if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码 { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //时间字符串里,必须是“/” var birthDate = new Date(strBirthday); var nowDateTime = new Date(); var age = nowDateTime.getFullYear() - birthDate.getFullYear(); //再考虑月、天的因素;.getMonth()获取的是从0开始的,这里进行比较,不需要加1 if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) { age--; } return age; } //根据身份证号码获取出生日期 function GetBirthDay(identityCard) { var len = (identityCard + "").length; if (len == 0) { return 0; } else { if ((len != 15) && (len != 18))//身份证号码只能为15位或18位其它不合法 { return 0; } } var strBirthday = ""; if (len == 18)//处理18位的身份证号码从号码中得到生日和性别代码 { strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2); } if (len == 15) { strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2); } //时间字符串里,必须是“/” var birthDate = new Date(strBirthday); var seperator1 = "-"; var year = birthDate.getFullYear(); var month = birthDate.getMonth() + 1; var strDate = birthDate.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var birthDay = year + seperator1 + month + seperator1 + strDate; return birthDay; } </script> </head> <body> <div id="myDiv"><h2>通过 AJAX 改变文本</h2></div> 身份证号码:<input id='idCard' type='text' /> 出生年月日:<input id='birthDay' type='text' /> 年龄:<input id='age' type='text' /> <button id="b01" type="button">根据身份证号码获取年龄</button> </body> </html>
感谢:https://www.cnblogs.com/ericli-ericli/p/4716761.html
https://www.cnblogs.com/wxdblog/p/6888240.html