原料:jquery
直接上代碼
html代碼
<html> <head> <title>$Title$</title> </head> <body> <input type="checkbox" value="男">男<br/> <input type="checkbox" value="女">女<br/> <input type="checkbox" value="男1">男1<br/> <input type="checkbox" value="女2">女2<br/> <input type="checkbox" value="男3">男3<br/> <input type="checkbox" value="女4">女4<br/> <input type="button" id="btn" value="btn"> <script src="/assets/js/jquery1.12.4.js"></script> </body> </html>
script代碼
<script> $("#btn").click(function () { var re = []; $("body").find("input[type='checkbox']:checked").each(function() {re.push($(this).val()); }) console.log(re.join("/")); }); ; </script>
實例:
結果:
另一種寫法(編譯器編輯 語法可能會變成紅色的,不影響使用)
原料:css3的選擇器
html代碼
<html> <head> <title>$Title$</title> </head> <body> <input type="checkbox" value="男">男<br/> <input type="checkbox" value="女">女<br/> <input type="checkbox" value="男1">男1<br/> <input type="checkbox" value="女2">女2<br/> <input type="checkbox" value="男3">男3<br/> <input type="checkbox" value="女4">女4<br/> <input type="button" onclick="box()" value="btn1" /> <script> function box() { var res = []; document.querySelectorAll("body input:checked").forEach((e)=>{ if(e.checked){ res.push(e.value); } }); console.log(res.join("/")); } </script> </body> </html>
結果: