根据性别选择不同的年龄(男和女对应不同的年龄阶段的选择)

时间:2021-10-29 14:18:57
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <span><input type="radio" name="sex" value="1" checked="checked" >男</span> <span><input type="radio" name="sex" value="2">女</span> <select name="num" id="age"> <option value="30">30</option> </select> </body> </html> <script src="jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function() { if($('[name="sex"]').val() == 1) { initAge(30, 50); } else if($('[name="sex"]').val() == 2) { initAge(40, 50); } $('[name="sex"]').change(function(e) { if(e.target.value == 2) { initAge(40, 50); } else if(e.target.value == 1) { initAge(30, 50); } }) $('[name="sex"]').change(function() { var index = $('input[name="sex"]:checked').val(); console.log(index); if(index == 1) { $('#age option:selected').html('2'); initAge(30, 50); } else if(index == 2) { $('#age option:selected').html('4'); initAge(40, 50); } }) function initAge(star, end) { $("#age").empty(); console.log(star, end); for(var i = star; i <= end; i++) { $('#age').append("<option value=" + i + ">" + i + "</option>"); } } }) </script>