Search the archives!
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Javascript] A loop this this script?
- From: rdong at advance.net (Roland Dong)
- Subject: [Javascript] A loop this this script?
- Date: Wed Jun 22 15:31:50 2005
Thanks so much Andrew! Now I understand why. Thanks for your explanation and solution. Roland -----Original Message----- From: javascript-bounces@xxxxxxxxxx [mailto:javascript-bounces@xxxxxxxxxx] On Behalf Of Andrew Clover Sent: Wednesday, June 22, 2005 3:34 PM To: [JavaScript List] Subject: Re: [Javascript] A loop this this script? Matt Warden <mwarden@xxxxxxxxx> wrote: > for (var i=0; i<navBar.length; i++) { > navBar[i].onmouseover=function() { > document.getElementById(ids[i]).style.visibility="visible"; > }; [...] > } This won't work because JavaScript is a late-evaluating language. That is, it evaluates the 'i' in the anonymous function getElementById call when it is used, *not* when the function is assigned. That is, *after* the loop, not *in* the loop. So when the onmouseover function eventually gets called, 'i' is equal to the value it had after the loop exited - namely navBar.length. There are lots of potential workarounds. Personally I'd try to cut down on the anonymous functions, and hide the extra information in a property on the page element (which its event handler will always have access to as 'this'): function hover_mouseover() { document.getElementById(this.hover_id).style.visibility= 'visible'; } [...] for (var i= navBar.length; i-->0;) { navBar[i].hover_id= ids[i]; navBar[i].onmouseover= hover_mouseover; navBar[i].onmouseout= hover_mouseout; } -- Andrew Clover mailto:and@xxxxxxxxxxx http://www.doxdesk.com/ _______________________________________________ Javascript mailing list Javascript@xxxxxxxxxx https://lists.LaTech.edu/mailman/listinfo/javascript
- References:
- [Javascript] A loop this this script?
- From: Andrew Clover
- [Javascript] A loop this this script?
- Prev by Date: [Javascript] A loop this this script?
- Next by Date: [Javascript] Need help determining when remote window closes.
- Previous by thread: [Javascript] A loop this this script?
- Next by thread: [Javascript] how to work around this?
- Index(es):