1. 程式人生 > >Jquery實現賬單全部選中和部分選中管理

Jquery實現賬單全部選中和部分選中管理

jquery

在做購物車系統是我們往往會遇到這樣一個需求,在點擊全選框時我們要將全部的單個賬單都選中;在單個選中賬單時,如果賬單全部被選中則需要全選框處於選中狀態,若沒有全部被選中則全選框處於沒選中狀態;

以下是在學習過程的實現代碼:

<script type="text/javascript">
$(document).ready(function(){
//刪除當前行商品元素
// $(".del").click(function () {
// $(this).parent().parent().remove();
// });
/* $(".del").on("click",function () {
$(this).parent().parent().remove();

}); */

$(".del").live("click",function () {
$(this).parent().parent().remove();
});

$(".add").click(function () {
//創建新節點
var $newPro = $("<tr>"
+ "<td>"
+ "<input name=‘‘ type=‘checkbox‘ value=‘‘ />"
+ "</td>"
+ "<td>"
+ "<img src=‘../image/computer.jpg‘ class=‘products‘ />"
+ "<a href=‘#‘>聯想筆記本電腦</a>"

+ "</td>"
+ "<td>¥3189元</td>"
+ "<td>"
+ "<img src=‘../image/subtraction.gif‘ width=‘20‘ height=‘20‘ />"
+ "<input type=‘text‘ class=‘quantity‘ value=‘1‘ />"
+ "<img src=‘../image/add.gif‘ width=‘20‘ height=‘20‘ />"
+ "</td>"
+ "<td><a href=‘#‘ class=‘del‘>刪除</a></td>"
+ "</tr>");
//在table中插入新建節點
$("table").append($newPro);
});
$("button").bind({
click:function(){},
mouseover:function(){ },
mouseout:function(){ }
});

$("th input[type=‘checkbox‘]").on("click",function(){
  if($(this).attr("checked")=="checked"){//點擊全選復選框 全選所有商品
    var $selectAll = $("tr td input[type=‘checkbox‘]");
    //alert($selectAll.length);
    $selectAll.each(function(){
    $(this).attr("checked","checked");
  });
}else{//點擊全選復選框 取消全選所有商品
  var $selectAll = $("tr td input[type=‘checkbox‘]");
  //alert($selectAll.length);
 $selectAll.each(function(){
  $(this).attr("checked",false);
 });
}
});
 $("tr td input[type=‘checkbox‘]").live("click",function (){//給所有的checkbox多選框綁定click事件
  var i =0;//聲明一個變量記錄選中的個數
  $("tr td input[type=‘checkbox‘]").each(function(){
    if($(this).attr("checked")=="checked"){//如果選中記錄數+1
      i=i+1;
    };
  });
  if(i==$("tr td input[type=‘checkbox‘]").length){//如果全部選中則將全選按鈕設為選中狀態
    $("th input[type=‘checkbox‘]").attr("checked","checked");
  }else{
    $("th input[type=‘checkbox‘]").attr("checked",false);
  };
 });
});
</script>

實現效果:

點擊全選----則商品內容全部選中 取消選中全選則全部取消 代碼天藍色部分效果如圖

技術分享技術分享

點擊添加按鈕可以添加預先設置好的元素及代碼藍色部分 效果如圖

技術分享

依次選中單個賬單,當賬單全部被選中時,全選按鈕被設為選中狀態,代碼紅色部分,若沒全部選中時則狀態不變 效果如圖

技術分享技術分享


Jquery實現賬單全部選中和部分選中管理