JavaScript购物车初成,未完结

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        <!--定义表格边框的样式-->
        table
        {
            border-collapse: collapse;
        }
        /*定义td的样式*/
        td
        {
            width: 100px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #000000;
            text-align: center;
        }
        /*定义文本域的样式*/
        #textarea0{
            font-size: 15px;
            text-align: center;
            line-height: 30px;
            height: 30px;
        }
    </style>
</head>
<body>
<script>
    //作业需求:
    // 1、在原来的基础上前面,加一列复选框,随机选择
    //2、在复选框后加用函数随机生成图片
    //3、将属性num一行用文本域代替



    //利用数组对象生成表格,表格循环都是双层循环,对象循环都用for( in ),


//    定义一组数组对象,前面多一列CheckBox和img图片
    var phoneList=[
        {type:"checked",img:"img/1.jpg",brand:"Apple",goods:"Iphone X",num:1, color:"black", price:7988},
        {type:"checked",img:"img/1.jpg",brand:"Oppo",goods:"Oppo R9",num:1, color:"black", price:2500},
        {type:"checked",img:"img/1.jpg",brand:"huaWei",goods:"HuaWei",num:1, color:"black", price:2588},
        {type:"checked",img:"img/1.jpg",brand:"Xiaomi",goods:"Note",num:1, color:"black", price:2488},
        {type:"checked",img:"img/1.jpg",brand:"Sanxing",goods:"sanxing",num:1, color:"black", price:8888},
    ];

//    定义循环的条件,i从0开始不断累加,直到长度小于phoneList.length
    for(var i=0;i<phoneList.length;i++){
//        如果满足条件,phoneList中的每一行中的type属性都为复选框
//        且随机生成的函数大于0.5时,复选框默认选中,否则不选中
//        每刷新一次,生成一次随机函数,复选框随机选中一次
        phoneList[i].type=Math.random()>0.5 ?"<input type='checkbox' checked>":"<input type='checkbox'>";
//       如果满足条件, phoneList中的num属性设置为:文本域的形式,
//        给文本域设置id,设置样式
        phoneList[i].num="<textarea id='textarea0'></textarea>";
//        如果满足条件, phoneList中的img属性,生成对应的地址的jpg图片
        phoneList[i].img="<img src='img/"+i+".jpg'>";
    }

//    调用函数,执行
    createTable(phoneList);

//    创建函数createTable(),这个函数的参数为data
    function createTable(data) {
//        定义一个表格,str+不断累加表格样式
        var str="<table>";
//        定义表头的tr,第一行字体加粗
        str+="<tr>";

//        执行th写入循环,
//        对象循环,用for( in ),
//        如果满足条件,将第一行(data[0])中的第一个属性(变量proto),写入th标签中间
        for(var proto in data[0]){
            str+="<th>"+proto+"</th>";
        }
//       表头的 tr标签结束
        str+="</tr>";

//        写入其他部分的tr(包含td的部分)

//        i初始值为0,每次累加1,当i的值小于参数的长度时,结束循环
        for(var i=0;i<data.length;i++){
//            写入tr
            str+="<tr>";
//            对象循环,继续使用for( in ),p为每一行(data[i])的属性,
            for(var p in data[i]){
//            写入td,且在td中写入phoneList每一行中的属性值
                str+="<td>" +phoneList[i][p]+"</td>"
            }
//            tr结束标签
            str+="</tr>";
        }
//        table结束标签
        str+="</table>";
//        写入页面
        document.write(str);
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/xzz2222/article/details/79619802
今日推荐