我曾经提出过一个有关如何避免在JS中编写HTML的问题,然后一些人告诉我可以使用JavaScript模板,例如jQuery/template插件等。
在生成静态HTML时,这是一个不错的思路,例如:
<ul id="productList"></ul>
<script id="productTemplate" type="text/x-jquery-tmpl"></script>
<script type="text/javascript">
var products = [
{ Name: "xxx", Price: "xxx" },
{ Name: "yyy", Price: "xxx" },
{ Name: "zzz", Price: "xxx" }
];
// Render the template with the products data and insert
// the rendered HTML under the "productList" element
$( "#productTemplate" ).tmpl( products )
.appendTo( "#productList" );
</script>
然而,当我试图将某些事件绑定到生成的html时,我遇到了一些问题。
例如,我有一个页面,用户可以通过价格/名称/位置搜索一些产品。
所以我有三个函数:
searchByPrice(lowPrice,highPrice,productType,currentPage)
searchByName(name,productType,currentPage);
searchByLocation(location,currentpage);
以上所有的功能在服务器端都有相关的方法,并且它们将使用 XML 格式返回产品。
由于它们将返回如此多的项目,因此我必须对它们进行分页,"currengPage" 用于告诉服务器端应返回哪些结果。
当客户端从服务器端获取结果后,现在可以使用 JavaScript 在 div 中显示它们,并在可能的情况下创建分页栏。
在了解模板之前,我会使用这种方式(我最讨厌的方式,尽力避免):
function searchByPrice(lowPrice,highPrice,productType,currentPage){
var url="WebService.asmx/searchByPrice?low="+lowPrice="&high="+highPrice+"&curPage="+currentPage;
//code to create the xmlHttp object
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var i=0;
var Prohtml="";
var proList=parseProductList(xmlhttp.responseText);
for(i=0;i<prolist.length;i++){
Prohtml+="<li><a href='#'>"+prolist[i].name+"</a> ("+prolist[i].price"+)</li>";
}
//generate the paging bar:
var totleResult=getTotleResultNumber(xmlhttp.responseText);
if(totleResult>10){
var paghtml="<span>";
//need the paging
var pagNum=totleResult/10+1;
for(i=1;i<=pagenum;i++){
paghtml+="<a onclick='searchByPrice(lowPrice,highPrice,productType,currentPage+1)'>i</a>";
//here the synax is not right,since I am really not good at handle the single or doule '"' in this manner.
//also if in the searchByName function,the click function here should be replaced using the searchByName(...)
}
}
}
}
}
在这个示例中,使用模板生成“Prohtml”非常容易,因为它们没有事件处理,但是对于“paghtml”,不同的搜索类型具有不同的点击功能。那么,如何处理呢?