Counter inconsistency in jQuery tmpl

I am trying to run a counter in my jQuery tmpl so that I can execute some logic after the template. The problem is that for some reason I can’t get the counter to increment by 1. It seems that it always increments by some random number.

Here is my HTML:

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

... and this is what I call the template engine:

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

I also added this to jsfiddle: http://jsfiddle.net/2ZtRL/1/

The result I would expect: 0 1 2 3 4 instead, I get 0 3 7 11 15

Totally strange! Help!

+4
source share
1 answer

Try the following:

 <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 the template template code as usual. You can see how it works here:

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

+3
source

Source: https://habr.com/ru/post/1380517/


All Articles