Underscore是一個非常實用的JavaScript庫,提供許多程式設計時需要的功能的支援,他在不擴充任何JavaScript的原生對象的情況下提供很多實用的功能。
無論你寫一段小的js代碼,還是寫一個大型的HTML5應用,underscore都能幫上忙。目前,underscore已經被廣泛使用,例如,backbone.js唯一強依賴的庫就是underscore.js。
Underscore.js學習資源:
Underscore.js 官網:http://underscorejs.org/#each
Underscore.js 中文文檔: http://www.css88.com/doc/underscore/
今天主要讨論Underscore 的前端模闆功能。它的模闆功能和前一篇介紹的javascript前端模闆是一樣的。對資料的處理更加友善。寫了個小例,供大家參考學習。
完整執行個體可以通過這個網址下載下傳:http://pan.baidu.com/share/link?shareid=2509652039&uk=688556984
<!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" target="_blank" rel="external nofollow" rel="stylesheet" type="text/css" />
<script src="jquery.js"></script>
<script src="underscore.js"></script>
</head>
<body>
</body>
</html>
<!--ace-template demo-->
<script id="t2" type="text/template">
<%_.each(datas, function(item) {%>
<div class="outer">
<div class="title">
<span ><%=item.film%></span>
</div>
<ul class="ul">
<%_.each(datas, function(item) {%>
<li>
<a href="<%=item.url%>" target="_blank" rel="external nofollow" >【<%=item.title%>】</a>
</li>
<%});%>
</ul>
</div>
<%});%>
</script>
<!--資料 -->
<script>
var datas = [
{
title: "一九四二",
url: "http://www.baidu.com",
film:"電影1"
},
{
title: "少年派的漂流",
url: "http://www.baidu.com",
film:"電影2"
},
{
title: "教父",
url: "http://www.baidu.com",
film:"電影3"
},
{
title: "肖申克的救贖",
url: "http://www.baidu.com",
film:"電影4"
},
{
title: "3d2012",
url: "http://www.baidu.com",
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
本文轉自挨踢前端部落格園部落格,原文連結http://www.cnblogs.com/duanhuajian/archive/2012/12/21/2826886.html如需轉載請自行聯系原作者
@挨踢前端