2010-02-17 6 views
3

Je suis plutôt doué avec jQuery mais quand j'arrive à des choses comme ça, j'ai besoin d'un peu d'aide.Comment raccourcir ce chargement jQuery?

Je veux raccourcir ce code:

$(function() { 
$('#experience_nav').click(function() { 
    $('#contentWrap').load('files.html #content_experience', function() { 
     $(this).hide().fadeIn(); 
     $('#content_experience').siblings().fadeOut(); 
    }); 

    return false; 
}); 
$('#aboutme_nav').click(function() { 
    $('#contentWrap').load('files.html #content_aboutme', function() { 
     $(this).hide().fadeIn(); 
     $('#content_aboutme').siblings().fadeOut(); 
    }); 

    return false; 
}); 
$('#recentclients_nav').click(function() { 
    $('#contentWrap').load('files.html #content_recentclients', function() { 
     $(this).hide().fadeIn(); 
     $('#content_recentclients').siblings().fadeOut(); 
    }); 

    return false; 
}); 
$('#contactme_nav').click(function() { 
    $('#contentWrap').load('files.html #content_contactme', function() { 
     $(this).hide().fadeIn(); 
     $('#content_contactme').siblings().fadeOut(); 
    }); 

    return false; 
}); 

}); 

Alors que je ne dois pas garder essentiellement d'appeler la même chose pour chaque instance différente.

Toute aide est géniale! Même en me disant que ça ne peut pas être fait! :-)

+0

rappelle d'accepter la réponse qui vous a le plus aidé! (en cliquant sur la coche grise sous les votes.) –

Répondre

9
// All <a>s wich the ID ends with '_nav' 
$('a[id$="_nav"]').click(function() { 
    var nav = $(this).attr('id').replace('_nav', ''); 

    $('#contentWrap').load('files.html #content_' + nav, function() { 
     $(this).hide().fadeIn(); 
     $('#content_' + nav).siblings().fadeOut(); 
    }); 

    return false; 
}) 
+0

Merci! Fonctionne parfaitement. Impressionnant! :-) – KayRoseDesign

+0

Pour le rendre plus léger dans ce cas: '$ ('a [id $ =" _ nav "]'). Live ('click', function() {' .... –

+0

@Nick Craver - Si vous n'avez pas besoin d'utiliser live() pourquoi utiliser live()? –

1

Essayez ce, en profitant de votre schéma de nommage:

$('#experience_nav, #aboutme_nav, #recentclients_nav, #contactme_nav').click(function() { 
    var id = '#content_' + $(this).attr('id').replace("_nav",""); 
    $('#contentWrap').load('files.html ' + id, function() { 
     $(this).hide().fadeIn(); 
     $(id).siblings().fadeOut(); 
    }); 
    return false; 
}); 

Alternativement, aussi légère que possible car il est accroché plusieurs fois:

$('[id$=_nav]').live('click', function() { 
    var id = '#content_' + $(this).attr('id').replace("_nav",""); 
    $('#contentWrap').load('files.html ' + id, function() { 
     $(this).hide().fadeIn(); 
     $(id).siblings().fadeOut(); 
    }); 
    return false; 
}); 
+0

Cela fonctionne parfaitement aussi bien Merci à vous deux :-) – KayRoseDesign