Generate unique id for each block in jQuery templating
I am generating a set of DIV tags using jQuery tempalting (http://api.jquery.com/jquery.tmpl/) for the json data which i receive with ajax.
I want to assign uniqe ids to the dynamically generated div's for further action on them.
i tried something like
var i = 0;
$( "#myTemplate" ).tmpl( data ).attr('id',++i).appendTo( "#container" );
but the value of i never changed. it assigned id=0 for all the 开发者_运维知识库div tags.
Now i got it working by doing a .each() and setting id by incrementing 'i' on all the matching div tags which have a common class assigned but i wanted to do it in one go.
Any idea?
I would go the other way - generate an id right in the template. Say, your template is:
<script id="divTemplate" type="text/html">
<div id='${getNextId()'}></div>
<div id='${getNextId()'}></div>
</script>
<script type="text/javascript">
var id = 1;
function getNextId()
{
return ++id;
}
</script>
That method will be called for every div, generating a new id in-place.
var d = new Date();
var i = d.getTime();
I think this could be a better option, as its inc milliseconds
OR
$.each('/selector goes here/',function (i,n){
$( "#myTemplate" ).tmpl( data ).attr('id',i).appendTo( "#container" );
});
You can't do it in one go in the example you posted. Since your method would only be called once, it's value would only be incremented once. .each
would be the way to go
Attr is not called for each item in the collection.
Rather atts uses the supplied values looping over the collection so i will not increase as you excpect.
精彩评论