Dynamic variables in attachEvent

C

comicgeekspeak

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.line;
var childcountid = jsonObj.lines.childcount;
var lineid = jsonObj.lines.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(newdiv);
}

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
 
M

Martin Honnen

for(var i = 0; i < 10; i++)
{
var linename = jsonObj.lines.line;
var childcountid = jsonObj.lines.childcount;
var lineid = jsonObj.lines.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);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top