前篇文章介绍了artTemplate相关使用的知识,这篇主要介绍artTemplate的两个常用方法:
1.template(‘search’,data);
第一个参数是script标签的id名
<script id="template" type="text/html">
<!--id名自定义,注意类型为text/html-->
第二个参数是要传入的数据
2.template.compile()
//根据模板生成渲染函数
var render = template.compile(tag);
//用数据渲染静态界面的内容
var html = render(data);
案例及代码:
1.template(‘search’,data);实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜索引擎art</title>
<script src="jquery-1.12.2.min.js"></script>
<script src="template-web.js"></script>
<script type="text/html" id="search">
//这种拼接方法在模板较多时使用优势更加明显
{{if s}}
<ul>
{{each s value i}}
<li>{{value}}</li>
{{/each}}
</ul>
{{/if}}
</script>
<script>
$(function(){
$("#txt").keyup(function(){
var txtValue = $("#txt").val();
$.ajax({
url:'https://www.baidu.com/su',
jsonp:'cb',
data:{wd:txtValue},
dataType:'jsonp',
success:function(data){
var html = template('search',data);
$("#info").html(html);
}
})
})
});
</script>
</head>
<body>
<div id="container">
<input type="text" id="txt">
<input type="button" value="查询" id="btn">
<div id="info"></div>
</div>
</body>
</html>
2.template.compile()实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>搜索引擎art</title>
<script src="jquery-1.12.2.min.js"></script>
<script src="template-web.js"></script>
<script type="text/html" id="search">
</script>
<script>
$(function(){
$("#txt").keyup(function(){
var txtValue = $("#txt").val();
$.ajax({
url:'https://www.baidu.com/su',
jsonp:'cb',
data:{wd:txtValue},
dataType:'jsonp',
success:function(data){
//每行标签开头加+和' 结尾加'
//模板内容较少时推荐,较多不推荐使用
var tag = '{{if s}}'
+ '<ul>'
+ '{{each s value i}}'
+ ' <li>{{value}}</li>'
+ '{{/each}}'
+ '</ul>'
+ '{{/if}}';
//根据模板生成渲染函数
var render = template.compile(tag);
//用数据渲染静态界面的内容
var html = render(data);
$("#info").html(html);
}
})
})
});
</script>
</head>
<body>
<div id="container">
<input type="text" id="txt">
<input type="button" value="查询" id="btn">
<div id="info"></div>
</div>
</body>
</html>
运行结果均为: