为 jQuery 模板中的每个块生成唯一的 id

发布于 2024-10-19 16:30:30 字数 412 浏览 9 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我喜欢麦丽素 2024-10-26 16:30:30

我会采用另一种方式 - 在模板中生成一个 id。假设您的模板是:

<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>

将为每个 div 调用该方法,就地生成一个新的 id。

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.

苏别ゝ 2024-10-26 16:30:30
var d = new Date();
var i = d.getTime();

我认为这可能是一个更好的选择,因为它包含毫秒

$.each('/selector goes here/',function (i,n){
    $( "#myTemplate" ).tmpl( data ).attr('id',i).appendTo( "#container" ); 
});
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" ); 
});
沙与沫 2024-10-26 16:30:30

在您发布的示例中,您无法一次性完成此操作。由于您的方法只会被调用一次,因此它的值只会增加一次。 .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

戏舞 2024-10-26 16:30:30

不会为集合中的每个项目调用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文