Inconsistent counter increment in jQuery tmpl
Asked Answered
O

1

6

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!

Oscitancy answered 10/11, 2011 at 5:46 Comment(0)
W
3

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

Whip answered 23/11, 2011 at 0:50 Comment(1)
Good workaround. Doesn't quite explain the weird behavior, but I can certainly do it this way.Oscitancy

© 2022 - 2024 — McMap. All rights reserved.