By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,299 Members | 1,054 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,299 IT Pros & Developers. It's quick & easy.

javascript dynamic function problem

chathura86
100+
P: 227
Expand|Select|Wrap|Line Numbers
  1.  
  2.             for (i = 0; i <= 30; i++)
  3.             {
  4.                 var obj = 'date_' + i;
  5.                 document.getElementById(obj).onmouseover = function (event) { alert(i) };
  6.             }
  7.  
date_1, date_2, date_3, ........., date_30 are hyperlink with those ids

i have added the above javascript to show the date on mouse over but no matter which date I go mouse over, it shows 30, and when i set i <= 10 it shows 10
i think it shows the final value of i,

please help me to fix it.

Regards
Apr 11 '09 #1
Share this Question
Share on Google+
3 Replies


Dormilich
Expert Mod 5K+
P: 8,639
what happened here is (in my opinion) that you incidentally run into a Closure. (this happens when you define a function inside another function or if events are incorporated) the interesting point is, that local variables (here i) are preserved.
Apr 11 '09 #2

chathura86
100+
P: 227
Thanks for the responce

any idea how to fix it?
Apr 12 '09 #3

Dormilich
Expert Mod 5K+
P: 8,639
e.g.
Expand|Select|Wrap|Line Numbers
  1. element.parameter = i;
  2. element.onmouseover = function() { alert(this.parameter); }
some more advanced one
Expand|Select|Wrap|Line Numbers
  1. element.parameter = i;
  2. var show = function() { alert(this.parameter); }
  3. element.addEventListener("mouseover", show, false);
  4. // or use the appropriate cross-browser solution
Apr 12 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.