469,626 Members | 876 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,626 developers. It's quick & easy.

Dynamic variables in attachEvent

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

Jan 24 '07 #1
1 1865
co************@gmail.com wrote:
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/
Jan 24 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.