Underscore.js 的模板功能介绍与应用
Underscore.js 的模板功能介绍与应用
发布时间:2016-12-30 来源:查字典编辑
摘要:Underscore是一个非常实用的JavaScript库,提供许多编程时需要的功能的支持,他在不扩展任何JavaScript的原生对象的情...

Underscore是一个非常实用的JavaScript库,提供许多编程时需要的功能的支持,他在不扩展任何JavaScript的原生对象的情况下提供很多实用的功能。

无论你写一段小的js代码,还是写一个大型的HTML5应用,underscore都能帮上忙。目前,underscore已经被广泛使用,例如,backbone.js唯一强依赖的库就是underscore.js。

今天主要讨论Underscore 的前端模板功能。它的模板功能和前一篇介绍的javascript前端模板是一样的。对数据的处理更加方便。写了个小例,供大家参考学习。

完整实例下载

复制代码 代码如下:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>Underscore</title>

<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>

<meta name="apple-mobile-web-app-capable" content="yes" />

<meta name="format-detection" content="telephone=no"/>

<link href="index.css" rel="stylesheet" type="text/css" />

<script src="jquery.js"></script>

<script src="underscore.js"></script>

</head>

<body>

</body>

</html>

<>

<script id="t2" type="text/template">

<%_.each(datas, function(item) {%>

<div>

<div>

<span ><%=item.film%></span>

</div>

<ul>

<%_.each(datas, function(item) {%>

<li>

<a href="<%=item.url%>">【<%=item.title%>】</a>

</li>

<%});%>

</ul>

</div>

<%});%>

</script>

<>

<script>

var datas = [

{

title: "一九四二",

url: "http://www.jb51.net",

film:"电影1"

},

{

title: "少年派的漂流",

url: "http://www.jb51.net",

film:"电影2"

},

{

title: "教父",

url: "http://www.jb51.net",

film:"电影3"

},

{

title: "肖申克的救赎",

url: "http://www.jb51.net",

film:"电影4"

},

{

title: "3d2012",

url: "http://www.jb51.net",

film:"电影5"

}

];

$("body").html( _.template($("#t2").html(), datas));

</script>

<>

<script type="text/javascript">

$('.ul').hide();

$('.ul>li:last-child').addClass('last-li');

$('body>div:first-child>ul').show();

$('.title').click(function(){

$(this).siblings().toggle();

$(this).parent().siblings().children('.bbs-nav-ul').hide();

}) $('.title').hover(function(){

$(this).toggleClass('hover');

})

$('.ul>li').hover(function(){

$(this).toggleClass('hover');

})

</script

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类