实例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin: 0; padding: 0; } .car{ width: 390px; height: 500px; border:1px solid #B30702; margin: 100px auto; } .top{ width: 390px; height: 45px; background:#B30702; color: white; text-align: center; line-height: 45px; } .item,.item1{ margin-top: 20px; } .item p,.item1 p{ display: inline-block; height: 30px; line-height: 30px; width: 70px; font-size: 14px; text-align: center; } .item1 input{ width: 90px; height: 30px; text-align: center; } span{ width: 90px; height: 30px; display: inline-block; border:1px solid #ccc; margin-left: 5px; line-height: 30px; text-align: center; font-size: 14px; } button{ width: 190px; height: 45px; background:#B30702 ; display:block; margin: 20px auto; color: white; border: none; outline: none; } .select{ border:1px solid #B30702; } </style> <script src="js/jquery-3.3.1.min.js"></script> </head> <body> <div class="car"> <div class="top">加入购物车</div> <div class="item" name='Edition'> <p>版本</p> <span>ONE A2001</span> <span>ONE A2002</span> <span>ONE A2003</span> </div> <div class="item" name='frameColor'> <p>机身颜色</p> <span>白色</span> <span>粉色</span> <span>蓝色</span> </div> <div class="item" name='PackageType'> <p>套餐类型</p> <span>官方标配</span> <span>套餐一</span> <span>套餐二</span> </div> <div class="item" name='Memory'> <p>机身内存</p> <span>16G</span> <span>32G</span> <span>64G</span> </div> <div class="item" name='Place'> <p>产地</p> <span>中国大陆</span> <span>港澳台</span> </div> <div class="item" name='price'> <p>价格</p> <span>999元抢购</span> </div> <div class="item1" name='num'> <p>数量</p> <input type="text" value="1" /> </div> <button id="btn">加入购物车</button> </div> </body> </html> <script> $(function(){ var obj={}; var flag=true; $('span').click(function(){ if($(this).hasClass('select')){ $(this).removeClass('select'); flag = false; }else{ $(this).addClass('select').siblings().removeClass('select'); flag = true; } }) $('#btn').click(function(){ $('.item').each(function(){ //children() 方法返回返回被选元素的所有直接子元素。 if($(this).children('span.select').length !=1){ flag = false; } else { var key = $(this).attr('name'); var val = $(this).children('span.select').text(); obj[key] = val; } }) if($('.item1 input').val() && $('.item1 input').val()>=1){ obj['num'] = $('.item1 input').val(); } else { alert('数量没选'); } if(flag){ console.log(obj); }else { alert('有选项没选'); } }) }) </script>
运行实例 »
点击 "运行实例" 按钮查看在线实例