Connecting Tech Pros Worldwide Help | Site Map

Dynamic variables in attachEvent

  #1  
Old January 24th, 2007, 05:15 PM
comicgeekspeak@gmail.com
Guest
 
Posts: n/a
Hi there,

I am trying to write a loop that will add 10 divs to the screen. Each
div will have an onclick event. The function that will be called
onclick requires a parameter. That parameter is dynamic based on the
index of the loop. In Firefox this is no problem. However in IE I get
some results that I wouldn't expect.

Here is my code:

for(var i = 0; i < 10; i++)
{
var linename = jsonObj.lines[i].line;
var childcountid = jsonObj.lines[i].childcount;
var lineid = jsonObj.lines[i].lineid;

var newdiv = document.createElement('div');
newdiv.setAttribute("id","main" + i);
if (navigator.appName == "Microsoft Internet Explorer")
{
//************ this is the problem area
*****************
newspan.attachEvent("onclick", function() {getCategories('main' +
i)});
}
else
{
newspan.setAttribute("onclick", "getCategories('main" + i + "')");
}
document.getElementById('container').appendChild(n ewdiv);
}

What happens is when the element is clicked the parameter being passed
to getCategories is always 'main9' IE always grabs the current value
of i, not the value of i at the stage of the loop that attachEvent was
called.

I'm going out of my mind trying to figure this out. Please, any help
will be greatly appreciated.

Bryan

  #2  
Old January 24th, 2007, 05:25 PM
Martin Honnen
Guest
 
Posts: n/a

re: Dynamic variables in attachEvent


comicgeekspeak@gmail.com wrote:
Quote:
for(var i = 0; i < 10; i++)
{
var linename = jsonObj.lines[i].line;
var childcountid = jsonObj.lines[i].childcount;
var lineid = jsonObj.lines[i].lineid;
>
var newdiv = document.createElement('div');
newdiv.setAttribute("id","main" + i);
newdiv.onclick = new Function ("evt", "getCategories('main" + i
+ "');");
is one way, another is
newdiv.onclick = function (n) {
return function (evt) { getCategories('main' + n); };
}(i);
--

Martin Honnen
http://JavaScript.FAQTs.com/
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
A Guide to Coding Cross-Browser Scripts Part 2: Event Normalization volectricity insights 3 February 7th, 2008 10:22 AM
parsing website with a "searching...." page Aaron answers 3 April 6th, 2007 07:05 PM
How can I have one function call another function dynamically? Randell D. answers 39 July 23rd, 2005 10:32 PM