开发者

JQuery Templates need to assign ID's

开发者 https://www.devze.com 2023-02-13 02:01 出处:网络
This is probably dead simple I\'m just not on the right track I bet. I have an array of JSON objects being returned from my WCF calls, read by a JQuery AJAX call.

This is probably dead simple I'm just not on the right track I bet.

I have an array of JSON objects being returned from my WCF calls, read by a JQuery AJAX call.

Lets say the object looks like this:

string Name
string BackgroundImage 

So I have a bunch of spans I want to lay down in my webpage and I want to give them unique IDs. I was able to do it this "bad" way by throwing an ID into 开发者_StackOverflow社区my json object

    $("#tabLink").tmpl(json.d).appendTo("#nav");

--

    <script id="tabLink" type="text/x-jQuery-tmpl">
        <span id="page{$id}" class="tabLinks" style="background-image:url(${BackgroundImage}")>Tab {$id}</span>
    </script>

I want to see:

<span id="page1" class="tabLinks" style="blahblahblah")>Tab {$id}</span>
<span id="page2" class="tabLinks" style="blahblahblah")>Tab {$id}</span>
<span id="page3" class="tabLinks" style="blahblahblah")>Tab {$id}</span>


One option is to pass an object containing the array to your template. Then, do your "each" in the template where you have $index available to you or you can explicitly keep track of the index and object.

Would be like:

<script id="tabLink" type="text/x-jQuery-tmpl">
      {{each items}}
        <span id="page${$index}" class="tabLinks" style="background-image:url(${BackgroundImage}")>Tab ${$index}</span>
      {{/each}}
 </script>

or:

<script id="tabLink" type="text/x-jQuery-tmpl">
      {{each(i, item) items}}
        <span id="page${i}" class="tabLinks" style="background-image:url(${BackgroundImage}")>Tab ${i}</span>
      {{/each}}
</script>

And called like:

$("#tabLink").tmpl({ items: json.d }).appendTo("#nav");

Sample here: http://jsfiddle.net/rniemeyer/JHACF/

Doesn't seem like $index is available when just passing an array to .tmpl, otherwise you would be set with just using $index.


I found one way, but it seems a little hacky..

before my .appendTo() I can add a prop in .js so that one is not needed in WCF..

    var x = 1;
    $.each(json.d, function (i, item) {
        item.ID = x++; 
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消