jQuery tmpl用法总结

之前很是头疼循环数据的渲染,搞一大堆的命名,一点点的赋值,很是麻烦,今天学习了一下jQuery插件tmpl,下面抛出一些使用方法,供以后参考:

官方网址:http://web.archive.org/web/20121014080309/http://api.jquery.com/jquery.tmpl/

github网址:https://github.com/jquery/jquery-tmpl        http://jquery.github.com/jquery-tmpl/demos/step-by-step.html


下面重点介绍一下使用方法:

首先介绍一下  模板和数据,不用说这两个肯定是不可缺少的

模板有两种定义方法,下面给出具体code

1.

var markup = "
  • Some content: ${item}.
    " + " More content: ${myValue}.
  • "; $.template( "movieTemplate", markup );

    2.

    
    

    这样就定义了两种模板,前一种写到script里边,后边一种写到html里边


    数据用json


    下面开始渲染模板
    $( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );
    $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
    注意:movies是json数据数组

    var movies = [  
                { Name: "The Red Violin", ReleaseYear: "1998" },  
                { Name: "Eyes Wide Shut", ReleaseYear: "1999" },  
                { Name: "The Inheritance", ReleaseYear: "1976" }  
            ]; 


    下面给出一些更深层次的操作数据的方法
    1.判断:



    2.遍历(tmpl会遍历普通数据,但是有时候数据是模板数据对象里边还嵌套这数组等等)
    var movies = [
        {
    	Title: "Meet Joe Black",
    	Languages: [
    	    { Name: "English" },
    	    { Name: "French" }
    	]
        }
    ];


    注意:判断语句里边不要加空格最好不要有空格


    3.在应用中有时候想给模板里边填充一部分html代码




    4.应用中有时候也需要对数据进行一下处理


    var markup = "
  • Some content: ${$item.myMethod()}.
    " + " More content: ${$item.myValue}.
  • "; $.template( "movieTemplate", markup ); $.tmpl( "movieTemplate", movies, { myValue: "somevalue", myMethod: function() { return "something"; } } ).appendTo( "#movieList" );


    你可能感兴趣的:(jQuery,前端数据模板)