Is this the right way to access array elements in jQuery?

I have two arrays. One for navigation, another for panels on the page. Arrays are the same size. One navigation button for one panel. This code works, but I'm sure there should be a better way to do this without setting up temporary variables.

$('.footer-nav li').click(function()
{
  var temp = $('.footer-nav li').index(this);
  var tArray = $('.about-bgs li');
  $('.about-bgs li').fadeOut();
  $(tArray[temp]).fadeIn();  //This is the line in question!
});

Any members?

+5
source share
2 answers

The jQuery callback for $(selector).each(callback) takes two parameters : indexand element. So you can write

$('.footer-nav li').each(function(index, element) {
  element.click( function(evt) {
    $('.about-bgs li').fadeOut();
    $('.about-bgs li').get(index).fadeIn();
  }); 
});

, ( ) ( ). , , .

, , ( , ):

var current = $('.about-bgs li').fadeOut();
var last = $('.about-bgs li .current');
if (current !== last) {
  last.removeClass('current').fadeOut();
  current.addClass('current').fadeIn();
}

DOM .current ( CSS/JS).

+2

, tArray[$(this)].fadeIn()

EDIT: . var tArray = $('.about-bgs li');, tArray.fadeOut();

0

All Articles