>  기사  >  웹 프론트엔드  >  장바구니 프로그램의 완전한 버전(JavaScript 코드)

장바구니 프로그램의 완전한 버전(JavaScript 코드)

高洛峰
高洛峰원래의
2016-11-26 10:13:401377검색

[javascript]
/***********************************장바구니 카테고리************** **** ************************/ 
 
    var product=function(productArr){/*商product类基类productArr=>array;productArr['ID'], productArr['name'],productArr['pic'],=productArr['lvs'],productArr['width'],productArr['thickness'],productArr['length'],productArr['open'], productArr['capacity']*/ 
        var _ID=productArr['ID'],_name=productArr['name'],_pic=productArr['pic'],_price=productArr['price'],_weight= productArr['weight'],_originalPrice=productArr['originalPrice'],_this=this; 
        this.num=productArr['num']; 
        this.getName=function(){ 
            return _name; 
            } 
        this.getID=function(){ 
            return _ID; 
            }    
        this.getPrice=function(){ 
            return _price; 
            } 
        this.getWeight=function(){ 
            return _weight; 
            } 
        this.getPic=function(){ 
            return _pic; 
            } 
        this.getOriginalprice=function(){ 
            return _originalPrice; 
            } 
        this.setNum=function(newNum){ 
            _this.num=newNum; 
            } 
        this.getTotal=function(){ 
            var total=_this.num*_this.getPrice(); 
            반품 총액; 
           }   
         
        } 
     
    var makeProductObj=function(gID,pID,num){//system造product对象函数,返回system造的product对象,gID=>数据组ID, pID=>商품ID 
            /*********제조 코드*********/ 
            var pData=[]; 
            (함수(gID,pID){ 
                $.ajax({ 
                  url:'/module/data/default.php?action=dataDetail&groupID='+gID+'&ID='+pID+'&r= '+newDate(), 
                   유형:'post', 
                  dataType:'xml', 
                 async:false, 
                    /**팩토리 메소드***/ 
                   성공:기능(dataXML ){ 
                       pData.price=$(dataXML).children('root').children('extend19').text();
                        pData.originalPrice=$(dataXML).children('root').children('extend9').text(); 
                       pData.weight=$(dataXML).children('root').children('extend21').text(); 
                       pData.name=$(dataXML).children('root').children('name').text(); 
                       pData.pic=$(dataXML).children('root').children('extend17').text(); 
                      } 
                   }); 
                })(gID,pID); 
            새 제품 반품({ 
                num:num, 
               name:pData.name, 
               ID:pID, 
               가격:pData.price, 
               pic:pData.pic, 
               Weight:pData.weight, 
                originalPrice:pData.originalPrice, 
               }); 
        } 
    var cartCookie=$.cookies.get('productItem');//cookie의 전체局变weight=>'商productID|数weight,商productID|数weight' 
    //alert(mockCookie) ; 
     
    var productCollection=function(){//商品搜集类 
            var products=[]; 
            var hasOne=function(productObj){ 
                var isOne=0; 
               for(var i=0;i                  if(products[i].getID()==productObj.getID()){ 
                     1=1; 
                       휴식; 
                      } 
                  } 
               return isOne; 
               } 
              var initProduct 
            /********초기 제품 배열 코드*************/ 
                     //alert(mockCookie); 
              if(cartCookie){ 
                initProduct=cartCookie.split(','); 
                 for(var i=0;i                   var _productTemp=initProduct[i].split('|'); 
                  var _proObj=new makeProductObj(4,parseInt(_productTemp[0]),parseInt(_productTemp[1])); 
                  if(hasOne(_proObj)!=1){ 
                   products.push(_proObj); 
                 } 
                } 
                     } 
           /*******초기 제품 배열 코드*************/ 
            
            this.addProduct=function(productObj){//添加商품 
                  if(hasOne(productObj )!=1){ 
                       products.push(productObj); 
                   } 
               } 
            this.delProduct=function(productObj){//删除商 품 
               var _tempProducts= []; 
               for(var i=0;i                  if(products[i].getID()!==productObj.getID()){ 
                    //console.log (제품[i].getID()); 
                       _tempProducts.push(products[i]); 
                      } 
                  } 
                   products=_tempProducts; 
               }//del 
            this.setNumByPid=function(pID,newNum){//设置商 품수량 
                 for(var k=0;k                        if( 제품[k].getID()==pID){ 
                          제품[k].setNum(newNum); 
                           휴식; 
                         } 
                    } 
              } 
            this.getProductById=function(pID) {//pID为商상품ID,获得商상품对象 
for(var j=0;j                                                           break; 이 function(){//제품 개체 배열 가져오기                                                                                                 > 모든 제품 중
var _needMoney=0; s[k].getTotal ();
}
return _needMoney;

장바구니 클래스, productCollection 대리자 개체입니다
var _productCollection='';
var _this=this;
this.setCollection=function(collection){//Set 컬렉션
        _productCollection =collection;
         _nowCollection=_productCollection;//동적 컬렉션 개체                                            컬렉션 개체
this.setTemp=function(){
 ~                                             var listProduct=_productCollection.getProducts() 0;i_this.temp [i] = []; );
if(needProduct!=false){
_nowCollection.delProduct(needProduct)
}
this.setNumByPid=function(pID,newNum){//특정 상품의 수량 설정 , pID->제품 ID
_nowCollection.setNumByPid(pID,newNum)
}                                    .getCurrentNumByPid=function(pID){//특정 제품의 수량을 가져옵니다. gt;제품 ID
var productObj=_nowCollection.getProductById(pID); 🎜>                                                                
.getTotalMoney=function(){//총액 가져오기
var _money=_nowCollection.getNeedMoney()
return _money; 단일 제품의 총 금액을 가져옵니다.
var _needProduct=_nowCollection.getProductById(pID); throw new Error('No such product');
🎜>           var _totalMoney=_needProduct.getTotal();                                                      .renderCart=기능 (){//렌더링 함수
                                                                 서브클래스에 구현됨throw new Error('오류, 이 메서드는 서브클래스에 구현되어야 합니다.');
                                                                                                   ; .com
_this.renderCart()
_this.bindEvent()
}
.get NewCollection=function(){//새 컬렉션 개체 가져오기
                                                                                    >                                        / **
> 렌더링
var _content='';                                                                     ().getProducts()[i]; ~                                     _content+=''+_productEach.getName()+'$'+_productEach.getOriginalprice()+'$'+_productEach.getPrice()+''+_productEach.getWeight()+'Kg-<스팬 클래스 ="red">'+_productEach.num+'+$'+_productEach. getTotal()+'삭제                             } 
                         //document.write(_content); 
                           //alert(_content); 
                         $('#checkCart').find('tr').eq(0).after(_content);//渲染面板 
                        $('.step_total').find( '.step_total_right') .children('span').html('$'+cartTest.getTotalMoney()); 
                         /**팝박스카운트**/ 
                }//renderCart 
            장바구니 Test.bindEvent=function(){ 
                                   var _this=this; 
                                  //alert($('#'+win1.ID).find('.cartList').eq(0).html()); 
                                 $('#checkCart').find('.cartList').each(function(index){ 
                                      var _ 각각=$(이것);
                                            _each.find('td:last').css('cursor','pointer').click(function(){ 
                                       //alert('删除'); 
                                              var _tempThis=$(this) ;;                                       $ (this).parents('tr').remove(); 
                                         /*******항목의 총액을 다시 계산합니다*******/ 
                                           $('.step_total').find('.step_total_right').children('span' ).html('$'+_this.getTotalMoney()); 
                                        /*******항목의 총액을 다시 계산합니다*******/ 
                           |           _each.children('td[ class=numJia]').css('cursor','pointer').click(function(){ 
                                           var _jiaThis=$(this); 
                                                //alert($(this).parents('tr').parents('table').find('input[type=hidden]').val()); 
                                                    _this.setNumByPid($(this).parents('tr').find('td:first').find('input[type=hidden]').val(),_this.getCurrentNumByPid($(this). parents('tr').find('td:first').find('input[type=hidden]').val())+1); 
                                                //alert(_jiaThis.parents('td').siblings('td[class=nowNum]').children('input').val()); 
                                              _jiaThis.siblings('td[class=nowNum]').html( 
                                                   _this.getCurrentNumByPid(_jiaThis.parents('tr').find('td:first').find('input[type =hidden]').val()) 
                                              ); 
                                               /***********특정 품목의 총액을 다시 계산합니다*************/
                                 _jiaThis.siblings('td[class=eachTotal]').children('span').html('$'+_this.getTotalMoneyByPid(_jiaThis.parents(' tr').find('td:first').find('input[type=hidden]').val())); 
                                                /***********특정 품목의 총액을 다시 계산합니다*************/
                                                 
                                              /*******항목의 총액을 다시 계산합니다*******/ 
                                 $('.step_total').find('.step_total_right').children('span') .html('$'+_this.getTotalMoney()); 
                                               /*******항목의 총액을 다시 계산합니다*******/ 
                                                });//클릭增加商상품량 
                                      _each.children('td[class=numJian]').css('cursor','pointer').click(function(){ 
                                                 var _jianThis=$ (this); 
                                              if(_this.getCurrentNumByPid($(this).parents('tr').find('td:first').find('input[type=hidden]').val()) >1){ 
                                                 _this.setNumByPid($(this).parents('tr').find('td:first').find('input[type=hidden]').val() ,_이 .getCurrentNumByPid($(this).parents('tr').find('td:first').find('input[type=hidden]').val())-1); 
                                               _jianThis.남매 ('td[class=nowNum]').html( 
                                                _this.getCurrentNumByPid($(this).parents('tr').find('td:first').find('input [유형=숨김] ').val()) 
                                             ); 
                                  /***********특정 품목의 총액을 다시 계산합니다***********/ 
                                            _jianThis.siblings('td[class=eachTotal]').children('span').html(' $'+_this.getTotalMoneyByPid(_jianThis.parents('tr').find('td:first').find('input[type=hidden]').val())); 
                                               /**
*/
                                  | *>*/
} // 현재 상품 수가 1보다 큰 경우
}) // 클릭하면 상품 수가 줄어듭니다. products
}); // 각
} // binevent
Carttest.touchoff () // 트리거

$ (Window) .unload (function () {// 페이지
// 경고('개 머리'); LastCollection = CartTest.getNewCollection ()
var _products = LastCollection.getProduts ()
//console.Loguts.length); VAR _C Artcookie = '';
var _Countnum = 0 ;
for(var i=0;i<_products.length;i++){
_cartCookie+=_products[i].getID()+'| '+_ 제품[i].num+','
_countNum+=_products[i].num*_products[i].getWeight();                            _cartCookie=_cartCookie.substring(0,_cartCookie.length-1); 
                           //alert(_cartCookie); 
                           //alert(_cuntNum); 
                           //alert(_countNum); 
                          $.cookies.set('productItem',_cartCookie);//设置cookie 
                         $.cookies.set('countNum',_countNum);//设양의 쿠키 
                       }); 
                       
                      $('#btn').click(function(){ 
                         /******************선택한 제품이 없으면 반품하세요*******************/ 
                          var _listProducts=cartTest.getNewCollection().getProducts();
if(_listProducts.length<0||_listProducts.length==0){ 
                               Alert('제품을 선택하세요!'); 
                               return; 
                             } 
                         window.location.href="http ://www.php1.cn/">                        }); 
               
            } 
    /***********************장바구니 카테고리**************************** **** ********/ 
     
    /******************인스턴스화된 개체*******************/  
    var productCollections= new productCollection(); 
    var cartTest=new cart(); 
    cartTest.setCollection(productCollections); 
    새로운 shoppingTrolley(); 

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.