在jQote中使用.data()方法 - 客户端模板插件

时间:2011-01-06 05:40:12

标签: jquery client-side-templating jqote

过去几周,我一直在使用jQote – client-side templating插件在运行时生成html片段。

几个月来,我一直在使用dom属性,如id,class,alt来存储关键数据。

现在,我开始了解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

1 个答案:

答案 0 :(得分:1)

JQuery中的.data()函数适用于html5数据元素。

含义

<li id="myId" data-food="value" > 

相同
$("#myId").data('food', 'value');

您可以在http://html5doctor.com/html5-custom-data-attributes/

上阅读有关html5数据元素的更多信息

更多关于http://api.jquery.com/jQuery.data/

的JQuerys数据函数