因為最近都在學jQuery,所以這幾天做的都是jQuery案例,這次做了一個表格類的,功能做的涵蓋比較多,增刪,全選,反選,批刪等,
給大家先看一下是什么樣子的。
現在開始實現它吧
一:首先你要先寫一下他的json數據,這樣才能在渲染數據
{ "personInfos" : [ { "address" : "黑龍江", "persons" : [ { "age" : 27, "name" : "孫三峰", "sex" : "男" }, { "age" : 23, "name" : "劉壯壯", "sex" : "男" }, { "age" : 18, "name" : "王大旭", "sex" : "男" } ] }, { "address" : "北京", "persons" : [ { "age" : 18, "name" : "王思聰", "sex" : "男" }, { "age" : 33, "name" : "郭德綱", "sex" : "男" }, { "age" : 18, "name" : "王大錘", "sex" : "男" } ] }, { "address" : "河北", "persons" : [ { "age" : 33, "name" : "王寶強", "sex" : "男" } ] } ] }
二:html布局
<div class="chose" id="checkBoxList"> <table id="tb" border="1" cellspacing="0" cellpadding="1"> <thead id="hide_tbody"> <th>年齡</th> <th>姓名</th> <th>性別</th> <th>家鄉</th> <th>操作</th> <th>選擇</th> </thead> <tbody id="tbody"> </tbody> </table> <div class="button"> <button id="check_all">全選</button> <button id="cancel">取消全選</button> <button id="back">反選</button> <button id="checkdelete">選擇刪除</button> </div> </div>
三: jq代碼(記得引入jq文件)
$.ajax({ url:"js/jqjson.json", //引入地址 type:"GET", //請求方式 async:false, //異步還是同步 cache:false, //是否有緩存 success:function(data){ // console.log(data); //打印是否有數據 var html=""; for(var i=0;i<data.personInfos.length;i++){ for(var j=0;j<data.personInfos[i].persons.length;j++){ // console.log(persons.name.length); html+= ` <tr> <td>${data.personInfos[i].persons[j].age}</td> <td>${data.personInfos[i].persons[j].name}</td> <td>${data.personInfos[i].persons[j].sex}</td> <td>${data.personInfos[i].address}</td> <td> <button class="add">新增</button> <button class="delete">刪除</button> </td> <td> <input type="checkbox" name="check" > </td> </tr> `; } } $('#tbody').html(html); } })
$(function() { //增加 $(".add").click(function(){ // alert(1); //找它的父級的父級克隆然后追加 var adda=$(this).parent().parent().clone(true); $("#tb").append(adda); }); //刪除 $(".delete").click(function(){ // alert(1); //找它的父級的父級克隆然后移除 $(this).parent().parent().remove() }); //全選 $("#check_all").click(function(){ $("#checkBoxList :checkbox").attr("checked", true); }); //取消全選 $("#cancel").click(function(){ $("#checkBoxList :checkbox").attr("checked", false); }); //反選 $("#back").click(function(){ $('input').each(function(){ $(this).prop("checked",!$(this).prop("checked")); }) }) //批刪 $("#checkdelete").click(function(){ // alert(1); $('input').each(function(){ if($(this).prop("checked")){ $(this).parent().parent().remove() } }) }) });
-- --END