js实现翻页后保持checkbox选中状态的实现方法

这里主要实现一个页面有两个分页,实现勾选互不影响,提交数据

php后端--这里需要去了解一下display和fetch的区别去看手册吧

    
	public function couponAdd(){
		$this->display('couponAdd');
	}
	
	public function product($model='product',$keyword=''){
		$keyword=I('keyword');
		if($keyword!=''){
			$where['name|commodity_code']=['like','%'.$keyword."%"];
		}
		
		$title=I('cid',' ');
		if($title!=null){
			$proMap['cid']=$title;
			$proMap['status']=2;
			$specs=M('product_specs')->where($proMap)->field('product_id')->select();
		}
		if($specs){
			$where['id']=['in',implode(',',array_unique(array_column($specs, 'product_id')))];
		}
		$map['status']=1;
		$lists=M('product_category')->where($map)->select();
		//获取列表数据
        //统计要查询数据的数量
        $page_size =1;//评论根据系统设置查询的条数
        $page = intval($_REQUEST['p']);
        if(empty($page))$page = 1;
        $limit = (($page-1)*$page_size).",".$page_size  ;
            
        $where['status']=1;
        $list = M($model)->where($where)->order('id desc')->limit($limit)->select();

        $count[0]['count'] = M($model)->where($where)->count("*");    
    	//end
    
        $param = '';
        $Page       = new \Think\Ajaxpage($count[0]['count'],$page_size, indexc,$param);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
        
        $this->assign('titId',$title);
        $this->assign('keyword',$keyword);
        $this->assign('pageProduct',$show);
        $this->assign('list',$lists);
        $this->assign('product', $list);
        $html['content'] = $this->fetch('product');
        $this->ajaxReturn($html);
	}
	
	public function category($model='product_category',$keywords=''){
		 //获取列表数据
        //统计要查询数据的数量
        $keywords=I('keywords');
		if($keywords!=''){
			$where['title']=['like','%'.$keywords."%"];
		}
        $page_size = C('LIST_ROWS'); 
        $page = intval($_REQUEST['p']);
        if(empty($page))$page = 1;
        $limit = (($page-1)*$page_size).",".$page_size  ;
        
    	//让分页支持多条件查询  
        $where['status']=1;
        
        $list = M($model)->where($where)->order('id desc')->limit($limit)->select();

        $count[0]['count'] = M($model)->where($where)->count("*");    
    
        $param = '';
        //$map['status'] = array('gt',1);
        $Page       = new \Think\Ajaxpage($count[0]['count'],$page_size, indexs,$param);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show       = $Page->show();// 分页显示输出
        
        $this->assign('keywords',$keywords);
        $this->assign('pageCate',$show);
        $this->assign('listCate', $list);
        $html['content'] = $this->fetch('category');
        $this->ajaxReturn($html);
	}

还有一个问题就是分页问题,这里都想不到咋处理,你可以在Think这个中添加一下代码,然后命名Ajaxpage.php,这里可以在url地址栏中不显示分页提交的数据

<?php
/**
 * ajax分页类,有namespace,使用方法:
 * 控制器直接$ajaxpage = new \Think\Ajaxpage($p1,$p2,$p3);
 * @param unknowtype
 * @return return_type
 * @author jachin  2020-04-17
 */
namespace Think;

class Ajaxpage {
    // 分页栏每页显示的页数
    public $rollPage = 5;
    // 页数跳转时要带的参数
    public $parameter  ;
    // 默认列表每页显示行数
    public $listRows = 20;
    // 起始行数
    public $firstRow ;
    // 分页总页面数
    protected $totalPages  ;
    // 总行数
    protected $totalRows  ;
    // 当前页数
    protected $nowPage    ;
    // 分页的栏的总页数
    protected $coolPages   ;
    // 分页显示定制
    protected $config  = array('header'=>'条记录','prev'=>'上一页','next'=>'下一页','first'=>'第一页','last'=>'最后一页','theme'=>' %totalRow% %header% %nowPage%/%totalPage% 页 %upPage% %downPage% %first%  %prePage%  %linkPage%  %nextPage% %end%');
    // 默认分页变量名
    protected $varPage;
 
 
    public function __construct($totalRows,$listRows='',$ajax_func,$parameter='') {
        $this->totalRows = $totalRows;
        $this->ajax_func = $ajax_func;
        $this->parameter = $parameter;
        $this->varPage = 'p' ;
        if(!empty($listRows)) {
            $this->listRows = intval($listRows);
        }
        $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
        $this->coolPages  = ceil($this->totalPages/$this->rollPage);
        $this->nowPage  = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
        if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
            $this->nowPage = $this->totalPages;
        }
        $this->firstRow = $this->listRows*($this->nowPage-1);
    }
 
     public function nowpage($totalRows,$listRows='',$ajax_func,$parameter='') {
        $this->totalRows = $totalRows;
        $this->ajax_func = $ajax_func;
        $this->parameter = $parameter;
        $this->varPage = 'p' ;
        if(!empty($listRows)) {
            $this->listRows = intval($listRows);
        }
        $this->totalPages = ceil($this->totalRows/$this->listRows);     //总页数
        $this->coolPages  = ceil($this->totalPages/$this->rollPage);
        $this->nowPage  = !empty($_GET[$this->varPage])?intval($_GET[$this->varPage]):1;
        if(!empty($this->totalPages) && $this->nowPage>$this->totalPages) {
            $this->nowPage = $this->totalPages;
        }
        $this->firstRow = $this->listRows*($this->nowPage-1);
 
        return $this->nowPage;
    }
 
    public function setConfig($name,$value) {
        if(isset($this->config[$name])) {
            $this->config[$name]    =   $value;
        }
    }
 
 
    public function show() {
        if(0 == $this->totalRows) return '';
        $p = $this->varPage;
        $nowCoolPage      = ceil($this->nowPage/$this->rollPage);
        $url  =  $_SERVER['REQUEST_URI'].(strpos($_SERVER['REQUEST_URI'],'?')?'':"?").$this->parameter;
        $parse = parse_url($url);
        if(isset($parse['query'])) {
            parse_str($parse['query'],$params);
            unset($params[$p]);
            $url   =  $parse['path'].'?'.http_build_query($params);
        }
        //上下翻页字符串
        $upRow   = $this->nowPage-1;
        $downRow = $this->nowPage+1;
        if ($upRow>0){
            $upPage="<a class='ajaxify' id='big' href='JavaScript:".$this->ajax_func."(".$upRow.")'>".$this->config['prev']."</a>";
        }else{
            $upPage="";
        }
 
        if ($downRow <= $this->totalPages){
            $downPage="<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$downRow.")'>".$this->config['next']."</a>";
        }else{
            $downPage="";
        }
        // << < > >>
        if($nowCoolPage == 1){
            $theFirst = "";
            $prePage = "";
        }else{
            $preRow =  $this->nowPage-$this->rollPage;
            $prePage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$preRow.")'>上".$this->rollPage."页</a>";
            $theFirst = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(1)' >".$this->config['first']."</a>";
        }
        if($nowCoolPage == $this->coolPages){
            $nextPage = "";
            $theEnd="";
        }else{
            $nextRow = $this->nowPage+$this->rollPage;
            $theEndRow = $this->totalPages;
            $nextPage = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$nextRow.")' >下".$this->rollPage."页</a>";
            $theEnd = "<a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$theEndRow.")' >".$this->config['last']."</a>";
        }
        // 1 2 3 4 5
        $linkPage = "";
        for($i=1;$i<=$this->rollPage;$i++){
            $page=($nowCoolPage-1)*$this->rollPage+$i;
            if($page!=$this->nowPage){
                if($page<=$this->totalPages){
                   $linkPage .= " <a class='ajaxify' id='big' href='javascript:".$this->ajax_func."(".$page.")'> ".$page." </a>";
                }else{
                    break;
                }
            }else{
                if($this->totalPages != 1){
                    $linkPage .= " <span class='current'>".$page."</span>";
                }
            }
        }
        $pageStr  =  str_replace(
            array('%header%','%nowPage%','%totalRow%','%totalPage%','%upPage%','%downPage%','%first%','%prePage%','%linkPage%','%nextPage%','%end%'),
            array($this->config['header'],$this->nowPage,$this->totalRows,$this->totalPages,$upPage,$downPage,$theFirst,$prePage,$linkPage,$nextPage,$theEnd),$this->config['theme']);
        return $pageStr;
    }
 
}
 

因为同一个页面有多个分页会出现很多问题,但是这不是唯一的方法,还有一个方法就是在Page中找到

红色的部分是注释掉,蓝色的是新加的

couponAdd.html页面

<div class="data-table table-striped form-item" id="tabss">
	<ul class="tab-nav nav tabs" >
		<li data-tab="tab1" class="current"><a class="tab" href="javascript:void(0);">商品</a></li>
		<li data-tab="tab2" ><a class="tab" href="javascript:void(0);">类目</a></li>
	</ul>
	<a class="confirm ajax-get btn submit-btn" id="deselect">清空选择</a>
	<a class="confirm ajax-get btn btn-return" id="allProduct">全部商品</a>
	<div id="tab1">/div>
	<div id="tab2"></div>
			        
</div>
<script type="text/javascript">

	//清除所有缓存数据sessionStorage
	$('#deselect').on('click',function(){
		sessionStorage.clear();
		$("#tabss").load(location.href);
		// location.reload();
	});
	$('#allProduct').on('click',function(){
		sessionStorage.setItem('flag',1);
		$("#tabss").load(location.href);
	})
	var init_id = 1;//初始化页面 init_id==1
	var current=$('.current .tab').text();
	$('.tabs li').click(function(){
		current=$(this).text();
		if(current=='商品'){
			indexc(init_id); 
		}else{
			indexs(init_id); 
		}
	});

	if(current=='商品'){
		indexc(init_id); 
	}

	function indexc(id){

		var keyword=$('#keyword').val();
		if(typeof(keyword)=='undefined'){
			keyword='';
		}
		var name=$('#name').val();

		if(typeof(name)=='undefined'){
			name='';
		}
	    var id = id;
	    //把数据传递到要替换的控制器方法中
	    $.ajax({
	        url:'{:U(product)}',
	        type:"GET",
	        async:false,
	        dataType:"JSON",
	        data:{'p':id,'keyword':keyword,'cid':name},
	        success:function(data){
	            $("#tab1").replaceWith(data.content);  //html块替换html的div
	        },
	        error:function(data){
	            console.log("4:ajax not run~");
	        }
	    });
	}
	     //初始化页面 init_id==1
	function indexs(id){
		var keywords=$('#keywords').val();
		if(typeof(keywords)=='undefined'){
			keywords='';
		}
	    var id = id;
	    //把数据传递到要替换的控制器方法中
	    $.ajax({
	        url:'{:U(category)}',
	        type:"GET",
	        async:false,
	        dataType:"JSON",
	        //data:{'p':id,'id':deal_id},
	        data:{'p':id,'keywords':keywords},
	        success:function(data){
	            $("#tab2").replaceWith(data.content);  //html块替换html的div
	        },
	        error:function(data){
	            console.log("4:ajax not run~");
	        }
	    });
	}
	
	$(function(){
	    showTab();
	    //搜索功能
	    $("#search").click(function() {
	        var url = $(this).attr('url');
	        var query = $('.search-form').find('input').serialize();
	        query = query.replace(/(&|^)(\w*?\d*?\-*?_*?)*?=?((?=&)|(?=$))/g,'');
	        query = query.replace(/^&/g, '');
	        if (url.indexOf('?') > 0) {
	            url += '&' + query;
	        } else {
	            url += '?' + query;
	        }
	        window.location.href = url;
	    });
	    
	    /* 状态搜索子菜单 */
	    $(".search-form").find(".drop-down").hover(function(){
	        $("#sub-sch-menu").removeClass("hidden");
	    },function(){
	        $("#sub-sch-menu").addClass("hidden");
	    });
	    $("#sub-sch-menu li").find("a").each(function(){
	        $(this).click(function(){
	            var text = $(this).text();
	            $("#sch-sort-txt").text(text).attr("data",$(this).attr("value"));
	            $("#sub-sch-menu").addClass("hidden");
	        })
	    });
	    
	});
	function setCateId(){
		obj = document.getElementsByName("cateId");
	    check_val = [];
	    not_check = [];
	    
	    for(k in obj){
	        if(obj[k].checked)
	            check_val.push(obj[k].value);
	        else
				not_check.push(obj[k].value);
	    }
	    if(sessionStorage.getItem('flag')!=null){
	    	sessionStorage.removeItem('flag');
	    }
	    var cate=sessionStorage.getItem('cateId');
	    if (cate != null) {
	    	cateId=JSON.parse(cate);
		    var cateIds = cateId.filter(function(e) { 
		    	return not_check.indexOf(e) < 0; 
		    });
		    var newcateId=cateIds.concat(check_val.filter(function(v) {
				return cateIds.indexOf(v) === -1
			}));
		    sessionStorage.setItem("cateId",JSON.stringify(newcateId));
		}else{
			sessionStorage.setItem("cateId",JSON.stringify(check_val));
		}
	};
	function setProductId(){
		obj = document.getElementsByName("productId");
	    check_val = [];
	    not_check = [];
	    
	    for(k in obj){
	        if(obj[k].checked)
	            check_val.push(obj[k].value);
	        else
				not_check.push(obj[k].value);
	    }
	    if(sessionStorage.getItem('flag')!=null){
	    	sessionStorage.removeItem('flag');
	    }
	    
	    var product=sessionStorage.getItem('productId');
	    if (product != null) {
	    	productId=JSON.parse(product);
		    var productIds = productId.filter(function(e) { 
		    	return not_check.indexOf(e) < 0; 
		    });
		    var newproductId=productIds.concat(check_val.filter(function(v) {
				return productIds.indexOf(v) === -1
			}));
		    sessionStorage.setItem("productId",JSON.stringify(newproductId));
		}else{
			sessionStorage.setItem("productId",JSON.stringify(check_val));
		}
	}
	
</script>

category.html页面

<div id="tab2" class="tab-pane in tab2" style="width: 60%;margin-top: 10px;">
	<div class="cf">
		<div class="search-form fr cf">
            <div class="sleft" style="margin-bottom: 10px;">
                <input type="text" name="keywords" id="keywords" class="search-input" value="{:I('keywords')}" placeholder="请输入关键词">
                <a class="sch-btn" href="javascript:;" id="search" onclick="indexs(1)"><i class="btn-search"></i></a>
            </div>
        </div>
    </div>
    <table>
        <thead>
            <tr>
            	<th style="width: 20%" class="row-selected">
                    <input class="checkbox" name="selectAlla" id="selectAlla" type="checkbox">
                </th>
                <th style="width: 40%">ID</th>
	            <th style="width: 40%">类目名称</th>
            </tr>
        </thead>
        <tbody>
        <notempty name="listCate">
        <volist name="listCate" id="vo">
            <tr>
            	<td style="width: 20%"><input class="cateId row-selected" type="checkbox" name="cateId" value="{$vo.id}"></td>
                <td style="width: 40%">{$vo.id}</td>
	            <td style="width: 40%">{$vo.title}</td>
            </tr>
            
        </volist>
        <else/>
        <td colspan="10" class="text-center"> aOh!</td>
        </notempty>
        </tbody>
    </table>
    <div class="page">
        {$pageCate}
    </div>
    <input  type="hidden"  id="msg" value=""  >
</div>
<script type="text/javascript">
//显示缓存中的数据,如果该数据存在,那么就check状态
	$().ready(function(){
    var cateId =JSON.parse(sessionStorage.getItem('cateId'));//获取sessionStorage中存放的值
		var allProduct=sessionStorage.getItem('flag');
		if(cateId!=null){
			flag=1;//文本框中的值有和当前页对应的值就选中
			flags=1;
	        $("input[name='cateId']").each(function(){
	            for(var i=0;i<cateId.length;i++){
	                if($(this).val()==cateId[i]){
	                    $(this).attr('checked',true);
	                    flag++;
	                }
	            }
	            flags++;
	        });
//判断该页面是否所有的选择都被选择,都被选择,那么就勾选表格头部的复选框
	        if(flag==flags){
	        	$("input[name='selectAlla']").each(function(){
		            $(this).attr('checked',true);
		        });
	        }
		}
//判断是否是全选状态
		if(allProduct==1){
//勾选表格所有的复选框
			$("input[name='cateId']").each(function(){
	            $(this).attr('checked',true);
	        });
//勾选表格头部的复选框
			$("input[name='selectAlla']").each(function(){
	            $(this).attr('checked',true);
	        });
		}
        
	});
 
	$(function() {
        var $selectAll = $("#selectAlla");
        $selectAll.click(function() {
            // alert($selectAll.prop("checked"));
            if ($selectAll.prop("checked") == true) {
                // 上面的复选框已被选中
                $(":checkbox[name='cateId']").prop("checked", true);
               
            } else {
                // 上面的复选框没被选中
                $(":checkbox[name='cateId']").prop("checked", false);
               
            }
//调用前面的函数
            setCateId();
        });
        //单个勾选复选框
        $(".cateId").click(function(){
			var option = $(".cateId");
			option.each(function(i){
				if(!this.checked){
					$("#selectAlla").prop("checked", false);
					return false;
				}else{
					$("#selectAlla").prop("checked", true);
				}
			});
			setCateId();
		});
    });
   

</script>

product.html页面

<div id="tab1" class="tab-pane in tab1" style="width: 60%;margin-top: 10px;">

	<div class="cf">
		<select name="findProductname" class="productname" id="name">
			<empty name="titId">
				<option value="">-----选择-----</option>
	            <volist name="list" id="vos" >
	            	<option value="{$vos.id}">{$vos.title}</option>
	            </volist>
			<else /> 
				<volist name="list" id="vos" >
	            	<option value="{$vos.id}" <eq name="vos.id" value="$titId" > selected </eq>>{$vos.title}</option>
	            </volist>
	            <option value="">-----选择-----</option>
			</empty> 
			
        </select>
		<div class="search-form fr cf">
	        <div class="sleft" style="margin-bottom: 10px;">
	            <input type="text" name="keyword" class="search-input" id="keyword" value="{:I('keyword')}" placeholder="请输入关键词">
	            <a class="sch-btn" href="javascript:;" id="search" onclick="indexc(1)"><i class="btn-search"></i></a>
	        </div>
	    </div>
	</div>
	<table>
	    <thead>
	        <tr>
	        	<th class="row-selected" style="width: 20%">
	                <input id="selectAll" name="selectAll" class="checkbox" type="checkbox">
	            </th>
	            <th style="width: 40%">商品编号</th>
                <th style="width: 40%">商品名称</th>
	        </tr>
	    </thead>
	    <tbody>
	    <notempty name="product">
	    <volist name="product" id="vo">
	        <tr>
	        	<td style="width: 20%"><input class="productId row-selected" type="checkbox" name="productId" value="{$vo.id}"></td>
	        	<td style="width: 40%">{$vo.commodity_code}</td>
                <td style="width: 40%">{$vo.name}</td>
	            
	        </tr>
	    </volist>
	    <else/>
	    <td colspan="10" class="text-center"> aOh!</td>
	    </notempty>
	    </tbody>
	</table>
	<div class="page">
	    {$pageProduct}
	</div>
</div>
<script type="text/javascript">
	$('.productname').on("change",function(){
		indexc(1);
		
	})
	$().ready(function(){
	    var productId =JSON.parse(sessionStorage.getItem('productId'));
	//获取sessionStorage中存放的值
			var allProduct=sessionStorage.getItem('flag');
			if(productId!=null){
				flag=1;//文本框中的值有和当前页对应的值就选中
				flags=1;
		        $("input[name='productId']").each(function(){
		            for(var i=0;i<productId.length;i++){
		                if($(this).val()==productId[i]){
		                    $(this).attr('checked',true);
		                    flag++;
		                }
		            }
		            flags++;
		        });
		        if(flag==flags){
		        	$("input[name='selectAll']").each(function(){
			            $(this).attr('checked',true);
			        });
		        }
			}
			if(allProduct==1){
				$("input[name='productId']").each(function(){
		            $(this).attr('checked',true);
		        });
				$("input[name='selectAll']").each(function(){
		            $(this).attr('checked',true);
		        });
			}
	        
		});
	$(function() {
        var $selectAll = $("#selectAll");
        $selectAll.click(function() {
            // alert($selectAll.prop("checked"));
            if ($selectAll.prop("checked") == true) {
                // 上面的复选框已被选中
                $(":checkbox[name='productId']").prop("checked", true);
            } else {
                // 上面的复选框没被选中
                $(":checkbox[name='productId']").prop("checked", false);
            }
            setProductId();
        });

        $(".productId").click(function(){
			var option = $(".productId");
			option.each(function(i){
				if(!this.checked){
					$("#selectAll").prop("checked", false);
					return false;
				}else{
					$("#selectAll").prop("checked", true);
					
				}
			});
			setProductId();
		});
    });
   
	
</script>

整个代码还是有问题的,我后期优化,比如当你勾选了全部选择,那么你去取消一个勾选的时候会出现一个问题

目前的方法是先取消选择,然后再去勾选单个复选框(这个是最笨的方法了,更优的方法后期在加)。

还有一个问题代码冗余,可以优化代码比如我之前在不断调试,所以就没有优化,setPriductId()和setCategory()这两个方法是否可以合并呢,通过传参来实现岂不是更好。我有想过全部用公共函数来实现

发布了20 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/jachinFang/article/details/105652359