jquery根据身份证号获取生日、年龄、性别
1.html
<input type="text" /> <input type="button" value="查询"/>
2.js
var getCode = function () { var ele = $("input").val(); var birth = ele.substring(6, 10) + "-" + ele.substring(10, 12) + "-" + ele.substring(12, 14); console.log(birth); var sex = ""; if (parseInt(ele.substr(16, 1)) % 2 == 1) { sex = "男"; } else { sex = "女"; } console.log(sex); //获取年龄 var myDate = new Date(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); var age = myDate.getFullYear() - ele.substring(6, 10) - 1; if (ele.substring(10, 12) < month || ele.substring(10, 12) == month && ele.substring(12, 14) <= day) { age++; } console.log(age); };
效果:
完整示例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery根据身份证号获取生日、年龄、性别</title> </head> <body> <input type="text" /> <input type="button" value="查询"/> <script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> var getCode = function () { var ele = $("input").val(); var birth = ele.substring(6, 10) + "-" + ele.substring(10, 12) + "-" + ele.substring(12, 14); console.log(birth); var sex = ""; if (parseInt(ele.substr(16, 1)) % 2 == 1) { sex = "男"; } else { sex = "女"; } console.log(sex); //获取年龄 var myDate = new Date(); var month = myDate.getMonth() + 1; var day = myDate.getDate(); var age = myDate.getFullYear() - ele.substring(6, 10) - 1; if (ele.substring(10, 12) < month || ele.substring(10, 12) == month && ele.substring(12, 14) <= day) { age++; } console.log(age); }; </script> </body> </html>
感兴趣的朋友可以使用本站在线HTML/CSS/JavaScript代码运行工具:测试上述代码运行效果。
另外,本站在线工具小程序上也有一款功能更加强大的身份证信息获取工具,感兴趣的朋友可以扫描如下小程序码查看:
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery页面元素操作技巧汇总》、《jQuery常见事件用法与技巧总结》、《jQuery常用插件及用法总结》、《jQuery扩展技巧总结》及《jquery选择器用法总结》