关于分页选中问题-超越昨天的自己系列(9)

  

关于分页选中问题

  一些管理后台,可能会遇到这样的场景:几百条数据分页罗列出来后,需要最这些数据选中操作。比如我在第5页选中3条数据,返回到第4页再选1条,然后对4条数据进行处理。
  能想到的比较原始的做法是这样的:
  1,页面维持一个选中的数据容器
  2,每次新查询,或者翻页,这些数据传回后台,后台再传回页面(不要使用session)
  3,等到选择完毕后进行操作,就依照这个数据容器中的内容为准。
 
  那么页面上维护住这个所谓的数据容器是关键:
 
比如说页面中的每条数据类似这种形式,每条数据前都有个checkbox来供选择:
  
          #foreach($temp in $!{blacklist})
            <tr align="center">
                <td><input name="chk_id" id="chk_id" type="checkbox" value="$temp.phone"></td>
                <td>$temp.phone</td>
                <td>$!{dateUtil.formatDateTime($!temp.gmtLast)}</td>
                <td>$!{dateUtil.formatDateTime($!temp.gmtFirst)}</td>
                <td>$temp.loginCount</td>
              </tr>
          #end

下面三个方法,就直接实现了这个容器的存取数据功能,依照这个基础,选中和不选中的操作就比较简单了

var selectPhones ='$!{selectPhones}'.split(",");
var selectPhonesNum = $!{selectPhonesNum};

function pushSelectPhone(phone){
        if(checkSelectPhone(phone) == -1){
            selectPhones.push(phone);
            selectPhonesNum++;
            jQuery("#selectPhones").val(selectPhones);
            jQuery("#selectPhonesNum").val(selectPhonesNum);
            jQuery("#showNum").html(selectPhonesNum);
        }
    }
    
function sliceSelectPhone(phone){
        var index = checkSelectPhone(phone);
        if(index != -1){
            selectPhones.splice(index,1);
            selectPhonesNum--;
            jQuery("#selectPhones").val(selectPhones);
            jQuery("#selectPhonesNum").val(selectPhonesNum);
            jQuery("#showNum").html(selectPhonesNum);
        }
    }

function checkSelectPhone(newPhone){
        var index = -1;
        for (var i=0;i<=selectPhones.length-1;i++) { 
            var oldPhone = selectPhones[i];
            if(newPhone == oldPhone){
                    index = i;
                    return i;
            }
        }
        return index;
    }

然后只要对每个checkbox进行绑定事件就好了:

jQuery("input[name='chk_id']").click(function(){
        var phone = jQuery(this).attr("value");
        if(jQuery(this).attr("checked")){
            pushSelectPhone(phone);
        }else{
            sliceSelectPhone(phone)
        }
    })

那么像全选啊,页面刷新进来的时候需要对这个页面已经选中过的数据表现为选中这些功能也是比较好实现了:

jQuery("#chk_all").click(function(){
        if(jQuery(this).attr("checked")){
            jQuery("input[name='chk_id']").each(function(index){
                pushSelectPhone(jQuery(this).val());
            })
        }else{
            jQuery("input[name='chk_id']").each(function(index){
                sliceSelectPhone(jQuery(this).val())
            })
        }
    })
jQuery("input[name='chk_id']").each(function(index){
        if(checkSelectPhone(jQuery(this).val()) != -1){
                 jQuery(this).attr("checked", "checked");
         }
    })

这个功能应该是比较常见的,这儿是我本人的一个思路和实现,暂时还没想出另外比较好的实现方式。

原文地址:https://www.cnblogs.com/killbug/p/3579387.html