0

I'm working on this currently:

  • I have a div "out" and a button "in".
  • Click the button, Create div "extra" and button "extra_b"
  • At the same time, "out"and "in" hide.
  • click "extra_b", "out"and "in" appears, and DELETE "extra" and button "extra_b"

Here is the sample:FIDDLE

It can't work, and after I checked console, It probably tells me:

inner.onclick=function(){ add(outer[i]) };

unable to pass the object of current out element to the function correctly:

function add(objectIn){
}

Could you please tell me how to pass the elements to a function in a recursion? And how to modify my current code to make it run correctly?

Thanks a lot!

Community
  • 1
  • 1
Darklizard
  • 377
  • 4
  • 17

2 Answers2

0

This is a common problem is JavaScript. When you are binding the onclick event, you are not using the current value of i but rather when the click happens, the last value of i is used.

So you have to do:

inner.onclick= (function(i){ return function(){ add(outer[i]) })(i);

Community
  • 1
  • 1
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • Many thanks!! And little mistakes on bracket in your code: inner.onclick= function(i){ return function(){ add(outer[i]) } }(i); – Darklizard Jun 18 '13 at 09:32
0

You can either create a new closure like Darhazer suggested, or you if you don't mind using jQuery you can use jQuery.proxy():

inner.onclick = $.proxy(add, window, outer[i]);
Strille
  • 5,741
  • 2
  • 26
  • 40