用Javascript实现Repeater

如何实现一个js版的repeater?

Asp.net WebForm的repeater控件挺好用,我想用js实现一个在Ajax应用中也该还不错!半年前做了一个jQuery.Repeater插件,并用在了一个项目中,如今拿来晒晒!
 

原理

项模板为HTML代码,插件接收json数据源,读取模板并创新每一项。
 

模板HTML

<ul  id='repeater1'>
      <li  class='itemtempplate'>{列名}</li>
</ul>

 

 

json数据源格式

自个捣鼓的东西格式就自个做主啦:-D . 如下:

{tablename:"表名",rows:[{"列1":"值1"},{"列2":"值2"}.....{"列n":"值n"}]}

 


扩展原生String对象

为方便使用扩展一个String对象

 

//扩展String
String.prototype.trim  =  function()  {  
        return  this.replace(/(^\s*)|(\s*$)/g,"");
}
//
String.prototype.Replace=function  (str1,str2){
        var  rs=this.replace(new  RegExp(str1,"gm"),str2);
        return  rs;
}

 

 

将json字符串转为对象

//将json数据转为对象
function    jsonStringToDataTable(jsondata){  
                try{  
                        var    table=eval("("+jsondata+")");  
                return    table;  
        }  
        catch(ex){  
                        return    null    ;  
        }  
}  


取网页元素自身HTML源码

由于有些浏览器(如firefox)不支持outerHTML,特写了一个toHTML的小插件。

 

//取自身HTML源码的插件.
jQuery.fn.extend({  
                toHTML:function(){  
                                var    obj=$(this[0]);  
                                if(obj[0].outerHTML){  
                                                return    obj[0].outerHTML;  
                                }  
                                else{  
                                                    if($('.houfeng-hidearea')==null    ||    $('.houfeng-hidearea')[0]==null    ){  
                                                                $('body').append("<div class='houfeng-hidearea' style='display:none;'></div>");  
                                                    }  
                                                    $('.houfeng-hidearea').css('display','none');  
                                                    $('.houfeng-hidearea').html('');  
                                                    obj.clone(true).prependTo('.houfeng-hidearea');  
                                                    var    rs=    $('.houfeng-hidearea').html();  
                                                    $('.houfeng-hidearea').html('');  
                                                    return    rs;  
                                    }  
                }  
});

 


插件主要代码

jQuery.fn.extend({
        Repeater:function(val,ItemCreatedCallBack){//设置或取得数据源
                    this.each(function(){
                            if(val==null  ||  val==undefined){//如果参数为空返回相应数据
                                                return  $(this).data("_DataSrc");//从缓存返回数据
                            }
                            else{//如果不为空设置数据源。
                                            //
                                            try{
                                            var  valtype=(typeof  val).toString();
                                            if(valtype=='string')
                                                        val  =jsonStringToDataTable(val).rows;
                                              }catch(ex){
                                                        return  ;
                                              }
                                            //
                                            var  domtype=$(this).find(".itemtemplate").attr('nodeName');//查找元素类型
                                            //
                                            if($(this).data("_ItemTemplate")==null  ){
                                                    $(this).data("_ItemTemplate",$(this).find(".itemtemplate").toHTML());
                                                    $(this).find(".itemtemplate").remove();
                                            }  
                                            var  TrContentTemplate=$(this).data("_ItemTemplate");
                                            //
                                            var  fileds=____FindFiled(TrContentTemplate);//找到所有列
                                            if(fileds==null  )return  false  ;
                                            var  filedscount=fileds.length;//计算列数
                                            ////
                                            $(this).data("_DataSrc",val);  //将数据放入缓存
                                            var  count=val.length;
                                            for(var  i=0;i<count  ;i++){
                                                  ////绑定列值
                                                  var  NewTrContent=TrContentTemplate;
                                                  //
                                                  NewTrContent=NewTrContent.Replace("{{","{#");
                                                  NewTrContent=NewTrContent.Replace("}}","#}");
                                                  for(  var  j=0;j<filedscount;j++){
                                                              NewTrContent=NewTrContent.Replace("{"+fileds[j]+"}",val[i][fileds[j].trim()]);
                                                  }
                                                  NewTrContent=NewTrContent.Replace("{#","{");
                                                  NewTrContent=NewTrContent.Replace("#}","}");
                                                  //
                                                  var  area=$(this).find('tbody');
                                                  if(area  ==null  )
                                                                area  =$(this);
                                                  //
                                                  area.append(NewTrContent);
                                                  if(ItemCreatedCallBack!=null  ){
                                                        ItemCreatedCallBack($(this).find(domtype+":last"));
                                                  }
                                            }
                                            //
                                            $(this).RepeaterSetItemClass($(this).data("_class1"),$(this).data("_class2"),$(this).data("_hoverClass"));
                            }
                    });
        },
        RepeaterClear:function  (){//清除数据
                this.each(function(){
                            if($(this).data("_ItemTemplate")==null  ){
                                    $(this).data("_ItemTemplate",$(this).find(".itemtemplate").toHTML());
                            }  
                            $(this).find(".itemtemplate").remove();
                });
        },
        RepeaterSetItemClass:function  (class1,class2,hoverClass){//行样式
                this.each(function(){
                        if(class1==null  ||  class2==null  ||  hoverClass  ==null  )
                                return  ;
                                //将设置存入缓存
                              $(this).data("_class1",class1);
                              $(this).data("_class2",class2);
                              $(this).data("_hoverClass",hoverClass);
                              //
                              if($(this).data("_DataSrc")!=null  ){
                                        var  domtype=$(this).find(".itemtemplate").attr('nodeName');
                                      //
                                      $(this).find(domtype).addClass(class1);
                                      $(this).find(domtype+":nth-child(even)").addClass(class2);
                                    // $(this).find(domtype+":first").removeClass(class1);
                                        //鼠标移动上去颜色变化
                                      $(this).find(domtype).hover(function(){$(this).addClass(hoverClass);},function(){$(this).removeClass(hoverClass);});  
                      }
              });
        }      
});
//查找字段公共方法.
function  ____FindFiled(str){//公共方法.
        var  myRegex  =  new  RegExp("\{.+?\}",  "gim");
        //var arr = myRegex.exec(str);
        var  arr=str.match(myRegex);
        if(arr  ==null  )return  null  ;
        var  count=arr.length;
        for(  var  i=0;i<count;i++)
        {
              arr[i]=arr[i].Replace("{","").Replace("}","");
        }
        return  arr  ;
}
//----------------------------------------------------------------------

挺乱的,但代码也简单,也有注释,不多说了:-D


如何使用

$('repeater1').Repeager(data,[ItemCreatedCallBack]);

ItemCreatedCallBack 为可选参数,可以说是项创建事件吧!


如何嵌套?

通过ItemCreatedCallBack回调(或称事件)

Demo - HTML模板:

 

<div  id="repeager1">  
    <div    class='itemtemplate'>  
                    <b>{列名}</b>  
                    <ul  class="subrepeager">  
                                    <!--每多一层嵌套  要  多一层大括号-->
                                    <li  class='itemtemplate'>{{列名}}</li>  
                    </ul>  
    </div>  
</div>  

Demo - js代码:

$(function{  
                $('repeater1').Repeager(data,itemCreate);      
});  
function    itemCreate(x){  
            // 在此绑定子repeater
            // 参数X是父repeater的项引用类型为jQuery对象,
            // 通过X取得子repeater要用的数据 并取数据源 在此绑定子repeater 绑定子repeater
}  

 

 

源码下载

单击此处下载

  

  

你可能感兴趣的:(JavaScript)