最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JavaScript模板引擎用法實例

 更新時間:2015年07月10日 17:13:17   作者:優(yōu)雅先生  
這篇文章主要介紹了JavaScript模板引擎用法,涉及javascript實現(xiàn)模板的定義與字符替換的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了JavaScript模板引擎用法。分享給大家供大家參考。具體如下:

這里介紹的這個模板引擎寫得短小精悍,非常值得一看

tmpl.js文件如下:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function() {
 var cache = {};
 this.tmpl = function tmpl(str, data) {
  // Figure out if we're getting a template, or if we need to
  // load the template - and be sure to cache the result.
  var fn = 
   !/\W/.test(str) 
   ? 
   cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) 
   :
   // Generate a reusable function that will serve as a template
   // generator (and which will be cached).
   new Function(
    "obj", "var p=[],print=function(){p.push.apply(p,arguments);};" +
    // Introduce the data as local variables using with(){}
    "with(obj){p.push('" +
    // Convert the template into pure JavaScript
    str
     .replace(/[\r\t\n]/g, " ")
     .split("<%").join("\t")
     .replace(/((^|%>)[^\t]*)'/g, "$1\r")
     .replace(/\t=(.*?)%>/g, "',$1,'")
     .split("\t")
     .join("');")
     .split("%>")
     .join("p.push('")
     .split("\r")
     .join("\\'") + 
    "');}return p.join('');"
   ); // Function ends
  // Provide some basic currying to the user
  return data ? fn(data) : fn;
 };
})();

index.html文件如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>JavaScript tmpl Use Demo</title>
  <script type="text/javascript" src="js/jquery.min.js"></script>
  <script src="./tmpl.js" type="text/javascript"></script>
   <!-- 下面是模板user_tmpl -->
  <script type="text/html" id="user_tmpl">
   <% for ( var i = 0; i < users.length; i++ ) { %>
   <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
   <% } %>
  </script>
  <script type="text/javascript">
  // 用來填充模板的數(shù)據(jù)
   var users = [
    { url: "http://baidu.com", name: "jxq"},
    { url: "http://google.com", name: "william"}
   ];
   $(function() {
   // 調(diào)用模板引擎函數(shù)將數(shù)據(jù)填充到模板獲得最終內(nèi)容
    $("#myUl").html(tmpl("user_tmpl", users));
   });
  </script>
 </head>
 <body>
  <div>
   <ul id="myUl">
   </ul>
  </div>
 </body>
</html>

希望本文所述對大家的javascript程序設(shè)計有所幫助。

相關(guān)文章

最新評論

措美县| 黄大仙区| 五寨县| 班玛县| 彭阳县| 南岸区| 修武县| 收藏| 阿坝县| 会昌县| 芒康县| 蕲春县| 南雄市| 安顺市| 桑日县| 囊谦县| 历史| 禹城市| 炉霍县| 威远县| 沙洋县| 丰城市| 荆门市| 沂南县| 石嘴山市| 岫岩| 邓州市| 长岭县| 延吉市| 崇义县| 东乡族自治县| 松阳县| 郓城县| 柘城县| 鄱阳县| 浮梁县| 霍邱县| 南昌市| 五大连池市| 砀山县| 辽宁省|