一、全選功能實現(xiàn)
1.在視圖文件中,我們需要添加一個全選的按鈕,類似于下面這樣的代碼:
<input type="checkbox" name="chkall" onclick="check_all(this)">
登錄后復(fù)制
其中,check_all()
函數(shù)的作用是全選或取消全選:
function check_all(obj){ $(':checkbox').prop('checked', $(obj).prop('checked')); }
登錄后復(fù)制
在這里,用到了jQuery的選擇器選擇所有的checkbox并使用prop()方法設(shè)置其checked屬性。
2.以ThinkPHP為例,我們假設(shè)已經(jīng)獲取到了需要進行全選的數(shù)據(jù),并將其傳遞到視圖頁面中,此時我們需要使用for循環(huán)遍歷每個數(shù)據(jù),并為其添加checkbox和ID,代碼如下:
<?php foreach($list as $data):?> <tr> <td><input type="checkbox" name="ckb[]" value="<?php echo $data['id'];?>" ></td> <td><?php echo $data['title'];?></td> </tr> <?php endforeach;?>
登錄后復(fù)制
在這里,為了方便操作,使用了數(shù)組傳遞checkbox的值,checkbox的名稱為ckb[]
,其對應(yīng)的value為該行數(shù)據(jù)的ID值。
3.此時我們只需要在提交表單的時候獲取到所有選中的checkbox并將其對應(yīng)的值組合成一個新的數(shù)組,就可以實現(xiàn)全選的功能了。具體實現(xiàn)代碼如下:
public function all(){ $ids = input('post.ckb/a'); if(empty($ids)){ return $this->error('請選擇要刪除的數(shù)據(jù)!'); } $ids = implode(',',$ids); $where['id'] = array('in',$ids); $result = db('table')->where($where)->delete(); if($result){ return $this->success('刪除成功!'); }else{ return $this->error('刪除失敗!'); } }
登錄后復(fù)制
在這里,input('post.ckb/a')
用于獲取提交表單時傳遞的所有checkbox的值,使用implode()
方法將其連接成字符串,并將其用于查詢數(shù)據(jù)庫中的數(shù)據(jù)。
二、批量刪除功能實現(xiàn)
實現(xiàn)批量刪除功能需要結(jié)合前面的全選功能,具體步驟如下:
1.首先,用戶需要選中需要刪除的數(shù)據(jù),然后點擊刪除按鈕(或其他自定義按鈕),這時需要獲取選中的數(shù)據(jù)并對其進行刪除操作。
2.為了方便操作,我們可以將所有選中的數(shù)據(jù)ID值合并成一個字符串(以英文逗號分隔),然后將其傳遞到下一個處理函數(shù)中。
3.使用where()函數(shù)將刪除條件設(shè)置為id in (ids)
(其中,ids為所有要刪除數(shù)據(jù)的ID),然后使用delete()函數(shù)刪除滿足條件的數(shù)據(jù)即可。
具體實現(xiàn)代碼如下:
public function delete(){ $ids = input('post.ids/s',''); if(empty($ids)){ return $this->error('請選擇要刪除的數(shù)據(jù)!'); } $where['id'] = array('in',$ids); $result = db('table')->where($where)->delete(); if($result){ return $this->success('刪除成功!'); }else{ return $this->error('刪除失敗!'); } }
登錄后復(fù)制
以上就是thinkphp如何實現(xiàn)全選和刪除功能的詳細內(nèi)容,更多請關(guān)注www.xfxf.net其它相關(guān)文章!