<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button id="btn">Button</button>
<script src="js/jquery-1.10.1.min.js"></script>
<script src="js/handlebars.js"></script>
<script id="mytemplate" type="text/x-handlebars-template">
<ul>
{{#each urls}}
<li>
<a href="{{url}}">{{text}}</a>
</li>
{{/each}}
</ul>
</script>
<script>
$(function(){
$("#btn").click(function(){
//1. 获取script中定义的内容
var source = $("#mytemplate").html();
//2. 将定义的内容编译
var template = Handlebars.compile(source);
//3. 传入json替换{{}}中的值,输出html
var data = {
"urls":[
{"text":"hello1","url":"http://www.sina.com"},
{"text":"hello2","url":"http://www.sina.com"},
{"text":"hello3","url":"http://www.sina.com"}
]
};
var html = template(data);
console.log(html);
$(html).appendTo($("body"));
});
});
</script>
</body>
</html>
Ajax模板的使用
最新推荐文章于 2023-04-02 15:25:51 发布