为 jQuery 模板中的每个块生成唯一的 id
我正在使用 jQuery tempalting (http://api.jquery.com/jquery.tmpl/) 为我通过 ajax 接收的 json 数据生成一组 DIV 标签。
我想将 uniqe id 分配给动态生成的 div,以便对它们进行进一步操作。
我尝试过类似的事情
var i = 0;
$( "#myTemplate" ).tmpl( data ).attr('id',++i).appendTo( "#container" );
,但我的价值从未改变。它为所有 div 标签分配了 id=0 。
现在我通过执行 .each() 并通过在所有匹配的 div 标签上递增“i”来设置 id,这些标签分配了一个公共类,但我想一次性完成它。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会采用另一种方式 - 在模板中生成一个 id。假设您的模板是:
将为每个 div 调用该方法,就地生成一个新的 id。
I would go the other way - generate an id right in the template. Say, your template is:
That method will be called for every div, generating a new id in-place.
我认为这可能是一个更好的选择,因为它包含毫秒
或
I think this could be a better option, as its inc milliseconds
OR
在您发布的示例中,您无法一次性完成此操作。由于您的方法只会被调用一次,因此它的值只会增加一次。
.each
将是正确的选择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。
相反,atts 使用提供的值在集合上循环,因此 i 不会按您的预期增加。
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.