2010-02-17 7 views
3

저는 jQuery에 꽤 잘 어울 렸습니다.하지만 이런 것들을 얻으려면 약간의 도움이 필요합니다. 그래서 기본적으로 각각의 서로 다른 인스턴스에 대해 같은 일을 계속 전화 할 필요가 없습니다이 jQuery로드를 줄이려면 어떻게해야합니까?

$(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; 
}); 

}); 

:

그래서 나는이 코드를 단축 할 수 있습니다.

아무 도움도 없습니다. 할 수 없다고 말하는 것조차! :-)

+0

이 동의 기억을 가장 도움이 된 답변! (투표 밑의 회색 눈금을 클릭하십시오.) –

답변

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

감사! 완벽하게 작동합니다. 굉장해! :-) – KayRoseDesign

+0

이 경우 좀 더 가볍게 만들 수 있습니다 :'$ ('a [id $ = "_ nav"]') live ('click', function() {'.... –

+0

@Nick Craver - If live()를 사용해야하는 이유는 무엇입니까? –

1

은 당신의 이름 지정 방식을 활용,이 시도 :

$('#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; 
}); 

을 다른 방법으로, 가능한 한 경량 그것을 여러 번 엮은 이후 :

$('[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

이것은 완벽하게 작동합니다. 두 분 모두에게 감사드립니다 :-) – KayRoseDesign

관련 문제