jQuery Templatesating - 将数据与模板DOM元素相关联 [英] jQuery Templating - Associating data to template DOM elements
问题描述
我正在使用jQuery的模板插件来渲染与之类似的几行:
var clientData = [
{名称:Rey Bango,id:1},
{name:Mark Goldberg,id:2},
{name:Jen Statford,id:3}];
< script id =clientTemplatetype =text / html>
< li>< $ {name}< / li>
< / script>
$(#clientTemplate)。tmpl(clientData).appendTo(ul);
我想知道是否可以使用 jQuery的数据功能能够将每个行项目关联回到更新的标识符。
通常你可以这样做:
$。each(clientData,function(idx,item){
$('< li>< / li>')。appendTo('ul#clientTemplate')
.text(item.name)
.data('clientId',item.id );
});
$('ul#clientTemplate li')。click(function(){
updateClient($(this).data('clientId'));
});
但是,当您模板化时,您没有这种类型的控件。
注意:我宁愿不使用新的隐藏元素将这些数据存储在每一行上,也可以不必使用元素上的其他属性。
想法?
谢谢
jQuery Templates插件包括 tmplItem 函数这可以让你回到与模板呈现的任何元素相关联的实际数据。
所以,你可以做一些类似的事情:
var client = $(li)。first()。tmplItem()。data
/ pre>
在这种情况下,
客户端
将是您的数据:{name:Rey Bango,id:1}
示例: ht tp://jsfiddle.net/rniemeyer/fvhj4/
I am using jQuery's template plugin rendering several row items similiar to this:
var clientData = [ { name: "Rey Bango", id: 1 }, { name: "Mark Goldberg", id: 2 }, { name: "Jen Statford", id: 3 } ]; <script id="clientTemplate" type="text/html"> <li><${name}</li> </script> $("#clientTemplate").tmpl(clientData).appendTo( "ul" );
I am wondering if it is possible to make use of jQuery's data function to be able to associate each row item back to an identifier for updating.
Normally you could do something like this:
$.each(clientData, function(idx, item) { $('<li></li>').appendTo('ul#clientTemplate') .text(item.name) .data('clientId', item.id); }); $('ul#clientTemplate li').click(function() { updateClient($(this).data('clientId')); });
However you don't have this type of control when templating.
Note: I'd rather not use new hidden elements to store this data on each row, or additional attributes on the elements if I don't have to.
Ideas?
Thanks
解决方案The jQuery Templates plugin includes the tmplItem function that allows you to get back to the actual data associated with any element rendered by a template.
So, you would be able to do something like:
var client = $("li").first().tmplItem().data
In this case
client
would be your data:{ name: "Rey Bango", id: 1 }
Sample here: http://jsfiddle.net/rniemeyer/fvhj4/
这篇关于jQuery Templatesating - 将数据与模板DOM元素相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!