jQuery Templating - Associating data to template DOM elements

非 Y 不嫁゛ 提交于 2019-12-14 00:55:58

问题


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


回答1:


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/




回答2:


This could be a workaround:

$("#clientTemplate").tmpl(clientData).filter("li").each(function(i){
   $(this).data(clientData[i].id);
}).appendTo( "ul" ); 

Hope this helps. Cheers



来源:https://stackoverflow.com/questions/5918295/jquery-templating-associating-data-to-template-dom-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!