实例
if($('span.box').length!=1){没有全部选择必选项}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <style> span { width: 100px; height: 30px; border: 1px solid #000; display: inline-block; text-align: center; line-height: 30px } .box { border: 2px solid red; } .buynow { border: 1px solid lightgray; width: 80px; height: 30px; text-align: center; line-height: 30px; cursor: pointer; } </style> </head> <body> <div style="width:400px;text-align: center;">请选择规格</div> <div> <p class="item" name="version"> <b>型号</b> <span>X23</span> <span>X30</span> <span>X88</span> </p> <p class="item" name="color"> <b>颜色</b> <span>红色</span> <span>黑色</span> <span>金色</span> </p> <p class="item" name="memory"> <b>内存</b> <span>32G</span> <span>64G</span> <span>128G</span> </p> <p class="buynow">加入购物车</p> </div> <script> $(document).ready(function () { $('span').click(function () { if ($(this).hasClass('box')) { $(this).removeClass('box'); } else { $(this).addClass('box').siblings('span').removeClass('box') } }) $('.buynow').click(function () { var from = {} var key, value $('.item').each(function () { if ($(this).children('span.box').length != 1) { alert('请选择全部的购物项') return false; } else { key = $(this).children('span.box').html() value = $(this).attr('name') from[key] = value; } }) console.log(from) }) }) </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例