JavaScript input mailbox Auto Prompt Instance code

Source: Internet
Author: User
Tags foreach

  This article mainly introduces JavaScript input mailbox automatic Prompt instance code, need friends can refer to the

Originally wanted to arttemplate source analysis of the comments put up to share, but after a year, can not find, had to analyze the template engine principles, their own attempt to   write the template engine to share with you, leave a souvenir, remember at that time also contrasted several template engine.   Here is the JS template engine, with native JavaScript syntax, so very similar to PHP's native template engine.       Front-End template engine role?   1. You can make the front-end development simpler by not having to use the + operator to stitch strings in order to generate a DOM structure, but only one element (the HTML template inside), or a variable (stored in the template), or a template file   2. Easy to maintain, reduce coupling, and if your DOM structure changes, you don't need to change the logical code, just change the corresponding template (file)   3. Can be cached, if your template is a similar. tpl file, then it can be loaded in a browser and saved. Speaking of. TPL files, you can do more than just caching, you can also do through the module loader       will. TPL as a module, that can load files on demand, not more provincial broadband, speed up the page?   4. And so on       front-end template engine principle?   principle is very simple is the object (data) + template (containing variables)-> string (HTML)       Front-End template engine how to achieve?   By parsing the template, according to the lexical, the template into a function, and then by calling the function, and passing objects (data), output string (HTML)   (of course, the specific also depends on the code)   like this: The   code is as follows: var TPL = ' I am <%= name%&gt, <%= age=> years old '; <%=xxx>% lexical, marked as variable   var obj = {    name: ' Lovesueee ',     age:24}; var fn = Engine.compile (TPL); Compiled into functions   var str = fn (obj);  //Render out string   &NBsp         Example:   code as follows: <! DOCTYPE html> <html> <head> <meta http-equiv= "Content-type" content= "text/html"; Charset=utf-8 "> <title>ice demo</title> <script src="/javascripts/jquery/jquery-1.7.2.js "> </script> <script src= "/javascripts/ice/ice.js" ></script> <body>     <div id= " Content "></div> </body>   <script type=" text/html "id=" TPL ">     <div>here is The render result:</div>     <%  = this.title ();%>     <table border=1>     <% for (var i=0,tl = this.trs.length,tr;i<tl;i++) { %>         <%   &NBSP ;         TR = this.trs[i];             if (tr.sex = = "female") {       %>       &NB Sp <tr>         <td><%= tr.name; %></td><td><%= Tr.age; %></td> <td><%= Tr.sex | | "Men"%></td>         </tr>         <%}%>     <% %>     </table>     <img src= "<%= this.href%>" >     <%= this.inc Lude (' tpl2 ', this); %> </script> <script type= "text/html" id= "TPL2" >     <div>here is the render result:</d iv>     <%  = this.print (' Welcome to Ice Template ');%>     <table border=1> &nbsp ;   <% for (var i=0,tl = this.trs.length,tr;i<tl;i++) { %>         <%             TR = this.trs[i];             if (Tr.sex = = "Men") {       %>       &NB Sp <tr>         <td><%= tr.name; %></td> <td><%= Tr.age; %></td>; td><%= Tr.sex | | "Men"%></td>         </tr>         <%}%>     <% %>     </table>     <img src= "<%= this.href%>" >   </script> <SC ript>     var trs = [        {name: "Stealth Killer", Age:29,sex: "Man"},         { Name: "Sola", Age:22,sex: "Men"},         {name: "Fesyo", Age:23,sex: "Female"},    ,     {name: "Love Demon Pot", Age:18,sex: "Men"},         {name: "Ryu-Qi", Age:25,sex: "Men"},    ,     {name: "You don't understand", Age:30,sex: "Female"}    ]      //var html = Ice ("TPL", {   //    Trs:trs, &N Bsp  //    HREF: "type4.jpg"    //},{   //    title:function () {  &N Bsp         Return "<p> This is a code snippet using the View helper output </p>"    //   } &nbsP  //});     var elem = document.getElementById (' TPL ');     var TPL = elem.innerhtml;       var html = Ice (tpl,{        Trs:trs,         href: "type4.j PG "   },{        title:function () {            return" ;p > This is a code fragment using the View helper output </p> "       }    }";     Console.log (HTML);     $ ("#content"). HTML (HTML);   </script> </html>         Simple implementation:     Code as follows: (function (Win) {     /template engine routing functions     var ice = function (ID, content) {        return ice[            typeof content = = ' object '? ' Render ': ' Compile '        ].apply (ice, arguments);    };         ice.version = ' 1.0.0 ';      //template configuration   &NBSp var iconfig = {        Opentag &nbsp: ' <% ',         Closetag: '%> '    };         var isnewengine =!! String.prototype.trim;      //Template cache     var Icache = Ice.cache = {};      //auxiliary functions     var ihelper = {        include:function (ID, data) {&NB Sp           return Irender (ID, data);        },         print:function (str) {          &NB Sp return str;        }    ;      //prototype inheritance     var iextend = Object.create | | Function (object) {        function Fn () {};         Fn.prototype = object; &nbs P       return new Fn;    };      //template compilation     var icompile = Ice.compile = function (ID, TPL, optioNS) {          var cache = null;           ID && (cache = Icach E[id]);           if (cache) {            return cache;     &NBS P            //[ID | tpl]         if (typeof TPL!== ' string ') {&nbsp ;             var elem = document.getElementById (ID);               options = TPL;               if (elem) {               //[I D, Options]                 options = TPL;                 TPL = Elem.value | | elem.innerhtml;              } else {               //[TPL Options]                 TPL = ID;                 ID = null;             {       }           options = opt ions | | {};         var render  = Iparse (TPL, Options);           ID && (Icache[id] = render);           return render;    };        //template rendering     var irender = Ice.render = function (ID, data, options) {          return Icompile (ID, Options) (data);    };         var Iforeach = Array.prototype.forEach?         function (arr, fn) {            Arr.foreach (FN)     &N Bsp  }:         function (arr, fn) {            for (var i = 0; ; Arr.length; i++) {          &NBsp     FN (Arr[i], I, arr)             {       };        //template resolution     var iparse = function (TPL, options) {        &NBSP ; var html = [];           var js = [];           var opentag = Options.opentag | | iconfig[' Opentag '];           var closetag = Options.closetag | | iconfig[' Closetag '];          //According to browser take different stitching string policy         var replaces = isnewengine   &NBS P        ? ["Var out= ', line=1;", "out+=", ";", "out+=html[", "];", "This.result=out;"            : ["Var out=[],line=1;",   "Out.push" (","); "," Out.push (html[","]); "," this . Result=out.join (");";          //function,         var body = replaces[0];           Iforeach (tpl.sPlit (Opentag), function (val, i) {              if (!val) {                return;                           var parts = val.split (Closeta g);               var head = parts[0];               var foot = parts[1];               var len = parts.length;            //html             if (len = = 1) {                body + + replaces[3] + html.length + replaces[4];                 Html.push (head);              } else {                  I F (head) {                   //code &NBSp                  //Remove space               &N Bsp     head = head                        . Replace (/^s +|s+$/g, ')                        -replace (/[nr]+s*/, ') & nbsp                      //Output statement           &N Bsp         if (head.indexof (' = ') = = 0) {                        head = head.substring (1). replace (/^[s]+|[ s;] +$/g, "");                           BODY = replaces[1] + head + RE PLACES[2];                    } else {            & nbsp           BODY = = Head;                                   & nbsp       Body + = ' line+=1;                     Js.push (head);                                //html                 if (foot) {              &NBSP ;     _foot = Foot.replace (/^[nr]+s*/g, ");                     if (!_foot) {          &NB Sp             return;                                   & nbsp     body + + replaces[3] + html.length + replaces[4];                   &nbsp Html.push (foot);                            }        });           BODY = "var render=function (data) {Ice.mix (this, data); try{"             + body             + replaces[5]             + "}catch (e) {ice.log (' rend error: ', line, ' line '); Ice.log (' Invalid statement: ', js[line-1]); throw e;};"             + "var proto=render.prototype=iextend (Ihelper);"         &NB Sp   + "Ice.mix (proto, Options);"             + "return function (data) {return new Render (d ATA). Result;}; ";           var render = new Function (' HTML ', ' JS ', ' iextend ', ' ihelper ', ' options ', body);           return render (HTML, JS, Iextend, Ihelper, Options);    };   &nbsp   Ice.log = function () {        if (typeof console = = ' undefined ') {      &NBS P     return;        }           var args = Array.prototype.slice.call (arguments);           console.log.apply && console.log.apply (console, args);      };      /merge object     Ice.mix = function (target, source) {        for (var key In Source {            if (Source.hasownproperty (key)) {        &NBSP ;       Target[key] = Source[key];            }         {   };      //Registration function     Ice.on = function (name, FN) {        ihelper[name] = fn;    };      //Clear cache     Ice.clearcache = function () {        Icache = {};    };      //change configuration     Ice.set = function (name, value) {        Iconfig[name] = Value    };      //exposure interface     if (typeof module!== ' undefined ' && module.exports) {    &N Bsp   Module.exports = template;    } else {        Win.ice = ice;    }  }) (window);  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.