javascript - jQuery incrementation param passing weird behavior -


let me describe scenario before question:

let counter defined number starting 0.

i have 2 tags: let them a1 , a2

i first dynamically added a1 html , used this:

jquery("a.adder").click(function(){adder(this, counter)}); 

then did counter++

then dynamically added a2 html , used again on both tags

jquery("a.adder").click(function(){adder(this, counter)}); 

then did counter++

also, in adder(param1, param2) , alert(counter)

okay here's question: after doing that, when clicked on a1 has 2 handlers, alert output 2 (it alerts twice each handler) , a2, alert 2 when clicked. why happening?

the reason returns 2 both anonymous functions creating closure on counter variable. means methods don't have current value of counter when bind them, have reference variable.

any changes in variable later on reflected in captured variable.

you can prevent creating new variable second binding:

var counter = 0; function adder(e, counter) {     alert(counter); }   jquery("<a class='adder'>a1</a><br />')").appendto("body"); jquery("a.adder").click(function(){adder(this, counter)}); counter++; var newcounter = counter; jquery("<a class='adder'>a2</a>')").appendto("body"); jquery("a.adder").click(function(){adder(this, c)}); counter++; 

here created new counter variable called newcounter capture second event handler.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -