0

I realise a similar issue has been asked here Javascript - Dynamically assign onclick event in the loop but I think I was a bit confused and couldn't add a comment.

I'm making a series of divs dynamically, in an array "newdiv". I want to create an onClick function which will expand the offsetHeight to the scrollHeight.

I'm trying to do this in my for loop as such:

newdiv[i].onclick = function() {expandThis(message_id) };

Where

message_id = message_array[i][0];

(the id column in the array, at message 'i')

The problem is familiar - all the made onClicks refer to the last message_id. Is there an easy way to make the onClick for newdiv[i] refer to message_array[i][0]?

Community
  • 1
  • 1
Nick
  • 33
  • 4
  • Seems like each div needs to know its own identity. Can you attach an arbitrary property to divs after you have added them to the DOM, such as newdiv[i].myid = i; then refer back to this property in your function: expandThis(this.myid);? – Matt Montag Aug 08 '11 at 09:16
  • @Matt M: The closure approach is much better; you just need to carefully close it over the right thing. – Jan Hudec Aug 08 '11 at 09:28

3 Answers3

1

You could use an anonymous function to create a closure to contain the value to be referred to.

function(message_id) {
  newdiv[i].onclick = function() {expandThis(message_id) };
}(message_array[i][0]);

JavaScript is a functional programming language without a let statement. So you have to write the equivalent closure, as ugly as it looks.

jasonc65
  • 51
  • 4
  • Isn't the `var` statement a *let*? – Jan Hudec Aug 08 '11 at 09:23
  • In a typical functional language such as Lisp, Ocaml, or Haskell, a let statement not only assigns a value to a name but also creates a closure. In JS, var will assign a name but does not create a closure. – jasonc65 Aug 08 '11 at 09:49
0

you could create the javascript code dynamically and store in in a var and then use the evalute() function and assign the result to your onclick callback.

0

You need to break the closure with message_id:

newdiv[i].onclick = (function(id) {
                       return function() {expandThis(id) };
                    }(message_id));

There are a million questions like this one, e.g. Do while javascript Problem.

Community
  • 1
  • 1
RobG
  • 142,382
  • 31
  • 172
  • 209