[thelist] Dereferencing in Javascript
Ben Glassman
bglassman at gmail.com
Wed Sep 27 08:32:41 CDT 2006
Thanks a lot. I understand the scope issue now. What do you mean exactly by
using an addEvent handler?
Ben
On 9/27/06, Christian Heilmann <codepo8 at gmail.com> wrote:
>
> > var headings = document.getElementsByTagName('h2');
> >
> > for(i = 0; i<headings.length; i++) {
> > var currentItem = document.getElementById('domain' + i);
> > headings[i].onclick = function() {
> > if (currentItem.className == 'show') {
> > currentItem.className = 'hide';
> > } else if (currentItem.className == 'hide') {
> > currentItem.className = 'show';
> > }
> > }
> > }
>
> This is a scope issue. Inside the anonymous function you define i is
> not defined as the current counter of the loop but will always be the
> final value of i. The quickest way around the issue is to define an
> own property of headings and use this, although I'd strongly advise to
> use an addEvent handler to do things like that.
>
> > for(i = 0; i<headings.length; i++) {
> headings[i].i = i;
> > headings[i].onclick = function() {
> > var currentItem = document.getElementById('domain' + this.i);
> > if (currentItem.className == 'show') {
> > currentItem.className = 'hide';
> > } else if (currentItem.className == 'hide') {
> > currentItem.className = 'show';
> > }
> > }
> > }
>
>
> --
> Chris Heilmann
> Book: http://www.beginningjavascript.com
> Blog: http://www.wait-till-i.com
> Writing: http://icant.co.uk/
> --
>
> * * Please support the community that supports you. * *
> http://evolt.org/help_support_evolt/
>
> For unsubscribe and other options, including the Tip Harvester
> and archives of thelist go to: http://lists.evolt.org
> Workers of the Web, evolt !
>
More information about the thelist
mailing list