?
Solved

dynamically adding onclick to div javascript help

Posted on 2009-02-11
5
Medium Priority
?
497 Views
Last Modified: 2012-05-06
hi all,

i've added an onclick method dynamically to a div

div.onclick = function() { alert(i); removeSection(i); };

where i is an integer in a for loop

now this seems to be working fine (if i break into this line it says i is incrementing as it should)

however when i click on the div the alert always reads 0.

any ideas why?

many thanks matt.
0
Comment
Question by:flynny
  • 3
  • 2
5 Comments
 
LVL 29

Expert Comment

by:Badotz
ID: 23613029
Where is "i" set?
0
 

Author Comment

by:flynny
ID: 23613126
Hi i've managed to work out what was going on

it seems that because i pass i to the method that i.e.

for(i=0;i<array;i++)
{
addsection(i);
}

addSection(i)
{
div.onclick = function() { alert(i); removeSection(i); };
}

that is aissigning the pointer rather than the value to the onclick event? so if i then create a local variable it works?

do you know why this is the case?

matt
0
 
LVL 29

Accepted Solution

by:
Badotz earned 2000 total points
ID: 23613392
Because this is wrong:

div.onclick = function() { alert(i); removeSection(i); };

It should be:

div.onclick = function(i) { alert(i); removeSection(i); };

You have to pass the variable all the way through.
0
 

Author Closing Comment

by:flynny
ID: 31545618
brilliant straight to the solution thanks for the help!
0
 
LVL 29

Expert Comment

by:Badotz
ID: 23613486
No worries - glad to help.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question