JavaScript输入邮箱自动提示实例代码
发布时间:2024-02-27 03:01:43
本来想把之前对artTemplate源码解析的注释放上来分享下,不过隔了一年,找不到了,只好把当时分析模板引擎原理后,自己尝试
写下的模板引擎与大家分享下,留个纪念,记得当时还对比了好几个模板引擎来着。
这里所说的js的模板引擎,用的是原生的javascript语法,所以很类似php的原生模板引擎。
前端模板引擎的作用?
1. 可以让前端开发更简单,不需要为了生成一个dom结构而使用+运算符去拼接字符串,而只需要一个元素的(里面的html模板),或者一个变量(存储着模板),或者一个模板文件
2. 易于维护,减少耦合,假使你的dom结构变化了,不需要更改逻辑代码,而只需要更改对应的模板(文件)
3. 可以缓存,如果你的模板是一个类似.tpl的文件,那么完全可以用浏览器去加载,并且还存下来。说到.tpl文件,可以做的不仅仅是缓存了,你还可以做到通过模块加载器
将.tpl作为一个模块,那就可以按需加载文件,不是更省宽带,加快页面速度吗?
4. 等等等
前端模板引擎的原理?
原理很简单就是 对象(数据)+ 模板(含有变量) -> 字符串(html)
前端模板引擎的如何实现?
通过解析模板,根据词法,将模板转换成一个函数,然后通过调用该函数,并传递对象(数据),输出字符串(html)
(当然,具体的还要看代码的)
就像这样:
var tpl = 'i am <%= name%>, <%= age=> years old'; // <%=xxx>% 词法,标记为变量
var obj = {
name : 'lovesueee' ,
age : 24
};
var fn = Engine.compile(tpl); // 编译成函数
var str = fn(obj); // 渲染出字符串
例子:
<!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++){ %>
<%
tr = this.trs[i];
if (tr.sex === "女") {
%>
<tr>
<td><%= tr.name;; %></td> <td><%= tr.age; %></td> <td><%= tr.sex || "男" %></td>
</tr>
<% } %>
<% } %>
</table>
<img src="<%= this.href %>">
<%= this.include('tpl2',this); %>
</script>
<script type="text/html" id="tpl2">
<div>here is the render result:</div>
<% = this.print('Welcome to Ice Template') ;%>
<table border=1>
<% for(var i=0,tl = this.trs.length,tr;i<tl;i++){ %>
<%
tr = this.trs[i];
if (tr.sex === "男") {
%>
<tr>
<td><%= tr.name;; %></td> <td><%= tr.age; %></td> <td><%= tr.sex || "男" %></td>
</tr>
<% } %>
<% } %>
</table>
<img src="<%= this.href %>">
</script>
<script>
var trs = [
{name:"隐形杀手",age:29,sex:"男"},
{name:"索拉",age:22,sex:"男"},
{name:"fesyo",age:23,sex:"女"},
{name:"恋妖壶",age:18,sex:"男"},
{name:"竜崎",age:25,sex:"男"},
{name:"你不懂的",age:30,sex:"女"}
]
// var html = ice("tpl",{
// trs: trs,
// href: "http://images.aspxhome.com/type4.jpg"
// },{
// title: function(){
// return "<p>这是使用视图helper输出的代码片断</p>"
// }
// });
var elem = document.getElementById('tpl');
var tpl = elem.innerHTML;
var html = ice(tpl,{
trs: trs,
href: "http://images.aspxhome.com/type4.jpg"
},{
title: function(){
return "<p>这是使用视图helper输出的代码片断</p>"
}
});
console.log(html);
$("#content").html(html);
</script>
</html>
简单的实现:
(function (win) {
// 模板引擎路由函数
var ice = function (id, content) {
return ice[
typeof content === 'object' ? 'render' : 'compile'
].apply(ice, arguments);
};
ice.version = '1.0.0';
// 模板配置
var iConfig = {
openTag : '<%',
closeTag : '%>'
};
var isNewEngine = !!String.prototype.trim;
// 模板缓存
var iCache = ice.cache = {};
// 辅助函数
var iHelper = {
include : function (id, data) {
return iRender(id, data);
},
print : function (str) {
return str;
}
};
// 原型继承
var iExtend = Object.create || function (object) {
function Fn () {};
Fn.prototype = object;
return new Fn;
};
// 模板编译
var iCompile = ice.compile = function (id, tpl, options) {
var cache = null;
id && (cache = iCache[id]);
if (cache) {
return cache;
}
// [id | tpl]
if (typeof tpl !== 'string') {
var elem = document.getElementById(id);
options = tpl;
if (elem) {
// [id, options]
options = tpl;
tpl = elem.value || elem.innerHTML;
} else {
//[tpl, options]
tpl = id;
id = null;
}
}
options = options || {};
var render = iParse(tpl, options);
id && (iCache[id] = render);
return render;
};
// 模板渲染
var iRender = ice.render = function (id, data, options) {
return iCompile(id, options)(data);
};
var iForEach = Array.prototype.forEach ?
function(arr, fn) {
arr.forEach(fn)
} :
function(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i], i, arr)
}
};
// 模板解析
var iParse = function (tpl, options) {
var html = [];
var js = [];
var openTag = options.openTag || iConfig['openTag'];
var closeTag = options.closeTag || iConfig['closeTag'];
// 根据浏览器采取不同的拼接字符串策略
var replaces = isNewEngine
?["var out='',line=1;", "out+=", ";", "out+=html[", "];", "this.result=out;"]
: ["var out=[],line=1;", "out.push(", ");", "out.push(html[", "]);", "this.result=out.join('');"];
// 函数体
var body = replaces[0];
iForEach(tpl.split(openTag), function(val, i) {
if (!val) {
return;
}
var parts = val.split(closeTag);
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 {
if (head ) {
// code
// 去除空格
head = head
.replace(/^\s+|\s+$/g, '')
.replace(/[\n\r]+\s*/, '')
// 输出语句
if (head.indexOf('=') === 0) {
head = head.substring(1).replace(/^[\s]+|[\s;]+$/g, '');
body += replaces[1] + head + replaces[2];
} else {
body += head;
}
body += 'line+=1;';
js.push(head);
}
// html
if (foot) {
_foot = foot.replace(/^[\n\r]+\s*/g, '');
if (!_foot) {
return;
}
body += replaces[3] + html.length + replaces[4];
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);"
+ "ice.mix(proto, options);"
+ "return function(data){return new Render(data).result;};";
var render = new Function('html', 'js', 'iExtend', 'iHelper', 'options', body);
return render(html, js, iExtend, iHelper, options);
};
ice.log = function () {
if (typeof console === 'undefined') {
return;
}
var args = Array.prototype.slice.call(arguments);
console.log.apply && console.log.apply(console, args);
};
// 合并对象
ice.mix = function (target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
};
// 注册函数
ice.on = function (name, fn) {
iHelper[name] = fn;
};
// 清除缓存
ice.clearCache = function () {
iCache = {};
};
// 更改配置
ice.set = function (name, value) {
iConfig[name] = value;
};
// 暴露接口
if (typeof module !== 'undefined' && module.exports) {
module.exports = template;
} else {
win.ice = ice;
}
})(window);


猜你喜欢
- Socket的基本背景在讨论这两个选项的区别时,我们需要知道的是BSD实现是所有socket实现的起源。基本上其他所有的系统某种程度上都参考
- 在输出代码行中,加入“index=False”如下:m_pred_survived.to_csv("clasified.csv&q
- 1、转化成时间格式seconds =35400m, s = divmod(seconds, 60)h, m = divmod(m, 60)p
- 简单替代密码简单替换密码是最常用的密码,包括为每个密文文本字符替换每个纯文本字符的算法.在这个过程中,与凯撒密码算法相比,字母表是混乱的.示
- 1、什么是版本控制系统版本控制是一种记录一个或若干个文件内容变化,以便将来查阅特定版本修订情况的系统。版本控制系统不仅可以应用于软件源代码的
- 本文实例讲述了python异常和文件处理机制。分享给大家供大家参考,具体如下:1 异常处理Python的异常用tryexceptfinall
- 一、场景说明在面试接口自动化时,经常会问,其他接口调用的前提条件是当前用户必须是登录状态,如何处理接口依赖?在此之前我们介绍过session
- 视图是 MTV 设计模式中的 V 层,它是实现业务逻辑的关键层,可以用来连接 M 层与 T 层,起着纽带般的作用,在《Django MTV和
- 问:怎样才能取得局域网中所有SQL Server的实例?答:请参考以下的具体步骤:SmoApplication.EnumAvailableS
- sysbench是一款非常优秀的基准测试工具,它能够精准的模拟MySQL数据库存储引擎InnoDB的磁盘的I/O模式。因此,基于sysben
- 我的读者知道我是一个喜欢痛骂Python3 unicode的人。这次也不例外。我将会告诉你用unicode有多痛苦和为什么我不能闭嘴。我花了
- 详解Python import方法引入模块的实例在Python用import或者from…import或者from…import…as…来导
- 在 settings.py 中添加以下内容:LOGGING = { 'version': 1,
- 今天有点囧a=['XXXX_game.sql', 'XXXX_game_sp.sql', 'XXXX
- 目录实验环境依赖项安装编程实现浏览器有一个可以用于展示网页的窗口代码总结实验环境操作系统:Linux Mint编辑器:vim编程语言:pyt
- 1.前言(闲话)最近在做电磁炮,发现题目需要用到颜色跟踪,于是花了一点时间学了一下OpenMV,只学习OpenMV是远远不够的,还需要实现与
- 一、form介绍我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。与此同
- 前言: json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps() 和 jso
- MySQL添加新用户,见文章底部。按照正常思维,创建用户和设置密码什么的,应该是一个动作完成的。然而事实并非如此。我每次都是通过在网上找代码
- 所有的前提都需要获取到root权限1.结束mysql进程//Linuxsudo services mysql stop//Macbrew s