Search the archives!
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Javascript] A loop this this script?
- From: and-babble at doxdesk.com (Andrew Clover)
- Subject: [Javascript] A loop this this script?
- Date: Wed Jun 22 14:35:04 2005
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/
- Follow-Ups:
- [Javascript] A loop this this script?
- From: Roland Dong
- [Javascript] how to work around this?
- From: Roland Dong
- [Javascript] A loop this this script?
- References:
- [Javascript] Need help determining when remote window closes.
- From: Glenn E. Lanier, II
- [Javascript] A loop this this script?
- From: Roland
- [Javascript] A loop this this script?
- From: Matt Warden
- [Javascript] Need help determining when remote window closes.
- Prev by Date: [Javascript] Need help determining when remote window closes.
- Next by Date: [Javascript] A loop this this script?
- Previous by thread: [Javascript] A loop this this script?
- Next by thread: [Javascript] A loop this this script?
- Index(es):