It's much cleaner to use $.each (no new variables will be introduced in the current scope), also with that you can avoid things like this. The problem is that in categories[index] index will be a reference to the variable you use in the loop, so every time the value of index changes it will "change" in the event handler as well. But not this way:
$.each(categories, function(index){ var nav_id = categories[ index ]['nav_id']; var data_id = categories[ index ]['data_id']; $('#' + nav_id).click( function(){ $('#' + data_id).slideToggle('slow'); } ); }) http://docs.jquery.com/Utilities On Nov 28, 8:01 pm, Ryan <[EMAIL PROTECTED]> wrote: > I have some 'NAV' elements, that when clicked should slideToggle their > respective 'DATA' elements. I am trying to do this by traversing an > Object with a for loop, and each elements IDs are stored in this data > structure. However, once execute, each click of any of the NAV > elements only slideToggles the last DATA element. > > Ex: > > Code: > > -- JAVASCRIPT > var categories = new Array(); > categories[1] = new Object; > categories[1]['nav_id'] = 'NAV_1'; > categories[1]['data_id'] = 'DATA_1'; > categories[2] = new Object; > categories[2]['nav_id'] = 'NAV_2'; > categories[2]['data_id'] = 'DATA_2'; > > -- JQUERY > for( var index in categories ){ > var nav_id = categories[ index ]['nav_id']; > var data_id = categories[ index ]['data_id']; > > $('#' + nav_id).click( function(){ > $('#' + data_id).slideToggle('slow'); > } > ); > > } > > -- HTML > <div id='NAV_1'> > </div> > <div id='NAV_2'> > </div> > > <div id='DATA_1'> > </div> > <div id='DATA_2'> > </div> > -- each div is absolutely positioned in the page > > I could possible see that JQuery could get confused by this, but to me > should be able to work somehow. Could there possibly be a way to do a > foreach() through element id's that match a certain regular > expression? > > Any help is greatly appreciated!