anushr
anushr

Reputation: 3400

Inconsistent counter increment in jQuery tmpl

I'm trying to have a counter running within my jQuery tmpl so that I can perform some post-template logic. The problem is that for some reason, I can't ever get the counter to increment by 1. It seems to always increment by some random number.

Here's my HTML:

<div id='myDiv'></div>
<script id='tpl'>
    ${i=0} 
    ${i++}
    ${i++}
    ${i++}
    ${i++}
</script>

... and here's how I'm calling the templating engine:

$.tmpl($('#tpl'), {}).appendTo("#myDiv");

I've put this up on jsfiddle also: http://jsfiddle.net/2ZtRL/1/

The output I'd expect is: 0 1 2 3 4 instead, I get 0 3 7 11 15

Completely bizarre! Help!

Upvotes: 6

Views: 1678

Answers (1)

superjaz1
superjaz1

Reputation: 436

Try this:

<div id='myDiv'></div>
<script type="text/javascript">
    var i = -1;
    function inc(){
        return ++i;
    }
</script>

<script id='tpl'>
    ${inc()}
    ${inc()}   
    ${inc()}
    ${inc()}
    ${inc()}   
    ${inc()}
</script>

And then call your template engine code as normal. You can see it working here:

http://jsfiddle.net/2ZtRL/12

Upvotes: 3

Related Questions