Connecting Tech Pros Worldwide Forums | Help | Site Map

Dynamic variables in attachEvent

comicgeekspeak@gmail.com
Guest
 
Posts: n/a
#1: Jan 24 '07
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


Martin Honnen
Guest
 
Posts: n/a
#2: Jan 24 '07

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