【发布时间】:2011-06-06 01:01:36
【问题描述】:
我问了一个关于如何避免在js中编写html的问题,然后有人告诉我使用javascript模板,例如jquery/template pugin等。
生成静态html是个好主意,例如:
<ul id="productList"></ul>
<script id="productTemplate" type="text/x-jquery-tmpl">
<li><a>${Name}</a> (${Price})</li>
</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”用于告诉服务器端应该返回哪部分结果。
当客户端从服务器端获取结果时,现在是 js 将它们显示在他的 div 中,并尽可能创建一个 Paging Bar。
在我知道模板之前,我就用这种方式(我最讨厌,尽量避免):
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”呢,不同搜索类型的点击功能不同。
那么,有什么好主意来处理这个吗?
【问题讨论】:
标签: javascript templates pagination