class属性知识点:
匹配类名元素:$('.class')
添加指定的类:$().addClass(class|fn)
删除指定的类:$().removeClass([class|fn])
检查元素是否含有某个特定的类:$().hasClass(class) 如果有,则返回true
切换类名:$().toggleClass(class|fn[,sw]) 如果存在(不存在)就删除(添加)一个类
案例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>1.23 点击商品选中效果(要求:控制台输出商品详情)</title> <script src="https://lib.baomitu.com/jquery/3.3.1/jquery.min.js"></script> <style> *{margin: 0;padding: 0;} .box{width: auto;border: 1px solid red;display: inline-block;margin: 50px;} .title{text-align: center;line-height: 40px;background: red;color: #fff;} .item,.item1{line-height: 28px;font-size: 14px;padding: 5px 10px;} .item b,.item1 b{width: 64px;display: inline-block;} .item span{margin-right: 10px;border: 1px solid #b9b9b9;width: 80px;text-align: center;display: inline-block;} .item span.on{border:1px solid red;color: red;} .item1 input{width: 50px;height: 28px;} .btn{border: none;line-height: 30px;background: red;color: #fff;margin: 0 0 30px 77px;padding: 0 15px;} </style> </head> <body> <div class="box"> <p class="title">请选择信息后加入购物车</p> <div class="goods"> <p class="item" name="version"> <b>版本</b> <span>A2001</span> <span>A111</span> <span>A222</span> </p> <p class="item" name="color"> <b>机身颜色</b> <span>白色</span> <span>黑色</span> <span>橙色</span> </p> <p class="item" name="type"> <b>套餐类型</b> <span>标配</span> <span>套餐一</span> <span>套餐2</span> </p> <p class="item" name="ram"> <b>运行内存</b> <span>3G</span> <span>6G</span> <span>9G</span> </p> <p class="item" name="rom"> <b>机身内存</b> <span>16G</span> <span>32G</span> <span>64G</span> </p> <p class="item" name="area"> <b>产地</b> <span>中国大陆</span> <span>港澳台</span> </p> <p class="item" name="price"> <b>价格</b> <span>666元</span> </p> <p class="item1" name="number"> <b>数量</b> <input type="number" name="number" id="number" min="1" value="1" /> </p> <button class="btn" id="btn">加入购物车</button> </div> </div> <script> $('.item span').click(function(){ if($(this).hasClass('on')){ $(this).removeClass('on'); }else{ $(this).addClass('on').siblings('span').removeClass('on'); } }) $('#btn').click(function(){ var flag = true; var goods={}; var arr = []; $('.item').each(function(){ arr.push($(this).children('span.on').length); if($(this).children('span.on').length != 1){ flag = false; }else{ var key = $(this).attr('name'); var val = $(this).children('span.on').html(); goods[key] = val; } }) if($('#number').val() <= 0 ){ alert('请选择***数量!'); flag = false; }else{ goods['number'] = $('#number').val(); console.log(goods); } if(flag){ alert('成功加入购物车'); } }) </script> </body> </html>
效果图: