实例
注意点:在FOR循环开始时声明变量,在FOR循环结束后输出对象
<!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 findbox = $(this).siblings('p').children('span.box'); var leng = findbox.length; var findbox2 = $('.item').children('b'); var leng2 = $('.item').length; if (leng != leng2) { alert('请选择全部的***项') return false; }else{ var from, key, value from = {} for (var i = 0; i < leng; i++) { key = findbox2[i].innerHTML value = findbox[i].innerHTML from[key] = value; } console.log(from) } }) }) </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例