【发布时间】:2011-01-06 05:40:12
【问题描述】:
在过去的几周里,我一直在使用jQote – client-side templating 插件在运行时生成 html 片段。
几个月来,我一直在使用 id、class、alt 等 dom 属性来存储关键数据。
现在,我开始了解 jquery 中的 .data() 方法来存储和检索数据。
在我的整个项目中,我都在使用模板动态生成 html 片段。
现在我需要知道如何在这些模板中动态使用 .data() 并将关键数据存储在任何动态创建的元素中。
模板js代码是这样的,
var template = templateCache.idOfTheTemplate; // say its a <li>
for(var i = 0; i < length; i ++){
$("#ulID").jqotepre(template, data);
}
模板:
<script id="idOfTheTemplate" type="text/template">
<li id="<%=this.id%>">//here i want to use .data() and store the id with different key
<a id="<%=this.id%>" href="#"><%=this.linkName%></a>
</li>
</script>
解决方案:
$("#ulID").jqotepre(template, data);
执行此行后,该元素在 DOM 中可用。
所以,你可以这样做,
$("#ulID").jqotepre(template, data);
$('#' + data.id).data('liInfo', data);//data.id is the ID of the li element in the DOM
【问题讨论】:
-
我没有使用客户端模板,但是如果您需要先将一些数据存储到您需要的元素中——它会找到这个元素,而不是在这个元素中存储数据。关于如何阅读/保存阅读这里-> api.jquery.com/jQuery.data
标签: jquery client-side-templating jqote