写重复函数的更好方法是什么?

时间:2014-05-18 21:34:44

标签: javascript jquery html

我有一个导航功能我已经创建了水平滚动我的网页,这很好但我猜它可以写得更好。任何人都可以给我建议我可以做什么逻辑明智地最小化我的代码?

的jQuery

$('.sectionOne').click(function(e){
    e.preventDefault();     
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-one').offset().left
    });       
});

$('.sectionTwo').click(function(e){
    e.preventDefault();    
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-two').offset().left
    });       
});

$('.sectionThree').click(function(e){
    e.preventDefault();   
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' :-$('.section-three').offset().left
    });       
});

$('.sectionFour').click(function(e){
    e.preventDefault();  
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-four').offset().left
    });       
});

$('.sectionFive').click(function(e){
    e.preventDefault();  
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-five').offset().left
    });       
});

$('.sectionSix').click(function(e){
    e.preventDefault(); 
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-six').offset().left
    });       
});

$('.sectionSeven').click(function(e){
    e.preventDefault();    
    $('nav').find('.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.section-seven').offset().left
    });       
});

HTML

<!-- Navigation -->
        <nav>
            <ol>
                <li><a href="#" data-section="section-one" class="active sectionOne">1</a></li>
                <li><a href="#" data-section="section-two" class="sectionTwo">2</a></li>
                <li><a href="#" data-section="section-three" class="sectionThree">3</a></li>
                <li><a href="#" data-section="section-four" class="sectionFour">4</a></li>
                <li><a href="#" data-section="section-five" class="sectionFive">5</a></li>
                <li><a href="#" data-section="section-six" class="sectionSix">6</a></li>
                <li><a href="#" data-section="section-seven" class="sectionSeven">7</a></li>
            </ol>
        </nav>

1 个答案:

答案 0 :(得分:4)

看起来非常多余。怎么样:

$('nav a').click(function(e){
    e.preventDefault();    
    $('nav a.active').removeClass('active'); 
    $(this).addClass('active'); 

    $('.scene').animate({
        'marginLeft' : -$('.' + $(this).attr('data-section')).offset().left
    });       
});
相关问题