第一种:用for循环遍历
!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Checkbox</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <p> <label for="hobby">Hobby: <input type="checkbox" name="hobby" value="reading" />阅读 <input type="checkbox" name="hobby" value="climbing" />爬山 <input type="checkbox" name="hobby" value="running" />跑步 <input type="checkbox" name="hobby" value="fishing" />钓鱼 <input type="checkbox" name="hobby" value="cooking" />做饭 </br></br> <input type="button" value="Get Value" onclick="getValue()" /> </label> </p> <span></span> <script> function getValue(){ var hobbies = document.getElementsByName("hobby"); var value=[]; for (i=0; i<hobbies.length; i++){ if (hobbies[i].checked){ value.push(hobbies[i].value); } } $("span").text(value);; } </script> </body> </html>
第二种方法:用each遍历
<script> function getValue(){ var hobbies = document.getElementsByName("hobby"); var value=[]; $.each(hobbies, function(i){ if (hobbies[i].checked) { value.push(hobbies[i].value) } }); $("span").text(value);; } </script>