js 自定义对象

1.代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title></title>
 <script src="../scripts/jquery-1.3.1.js" type="text/javascript"></script>
 <script language="javascript">
  
  
  jQuery(document).ready(function(){
   var setAmount={
     min:1,
     max:9,
     reg:function(x){
      return new RegExp("^[1-9]\\d*$").test(x);
     },
     amount:function(obj,mode){
      var x=$(obj).val();
      if (this.reg(x)){
       if (mode){
        x++;
       }else{
        x--;
       }
      }else{
       alert("请输入正确的数量!");
       $(obj).val(1);
       $(obj).focus();
      }
      return x;      
     },
     reduce:function(obj){
      var x=this.amount(obj,false);
      if (x>=this.min){
       $(obj).val(x);
      }else{
       alert("商品数量最少为"+this.min);
       $(obj).val(1);
       $(obj).focus();
      }
     },
     add:function(obj){
      var x=this.amount(obj,true);
      if (x<=this.max){
       $(obj).val(x);
      }else{
       alert("商品数量最多为"+this.max);
       $(obj).val(9);
       $(obj).focus();
      }
     },
     modify:function(obj){
      var x=$(obj).val();
      if (x<this.min||x>this.max||!this.reg(x)){
       alert("请输入正确的数量!");
       $(obj).val(1);
       $(obj).focus();
      }
     }
    };
    $("#add").click(function(){
      setAmount.add('#num');
     });
    $("#reduce").click(function(){
     setAmount.reduce('#num');
    });
    $("#num").keyup(function(){
     setAmount.modify('#num');
     });
    
   });
  </script>
</head>
<body>
<input type="button" id="add" value="+"/>
<input type="text"  id="num" value="1" style="width:50px"/>
<input type="button"id="reduce"  value="-"/>
  
</body>
</html>
2.效果

posted @ 2012-03-27 12:00  shuaisam  阅读(241)  评论(0)    收藏  举报