开发者

jQuery incrementation param passing weird behavior

开发者 https://www.devze.com 2023-03-17 00:28 出处:网络
Let me describe my scenario before I say my question: Let counter be defined already as a number starting from 0.

Let me describe my scenario before I say my question:

Let counter be defined already as a number starting from 0.

I have 2 a tags: let them be a1 and a2

I first dynamically added a1 into my htm开发者_如何学编程l and then used this:

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

then I did counter++

then I dynamically added a2 into my html and then used this again on both my a tags

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

then I did counter++

also, in my adder(param1, param2) , all I do is alert(counter)

Okay here's my question: After doing all that, when I clicked on a1 which has 2 handlers, the alert output is 2 (it alerts twice for each handler) and for a2, the alert is also 2 when clicked. Why is this happening?


The reason it returns 2 for both is that your anonymous functions are creating a closure over the counter variable. What this means is that those methods don't just have the current value of counter when you bind them, they have a reference to the variable.

Any changes in that variable later on will be reflected in the captured variable.

You can prevent this by creating a new variable for the 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 is created a new counter variable called newCounter which is capture by the second event handler.


you made two click events, and your click events return the current value of 'counter'

0

精彩评论

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

关注公众号