V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zebulon
V2EX  ›  问与答

有没有办法能简化这段代码

  •  
  •   zebulon · 2016-01-20 10:11:07 +08:00 · 2116 次点击
    这是一个创建于 3025 天前的主题,其中的信息可能已经有所发展或是发生改变。

    $('.tabs ul li').eq(0).click(function(){
    $('body,html').animate({scrollTop: $('#tab1').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(1).click(function(){
    $('body,html').animate({scrollTop: $('#tab2').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(2).click(function(){
    $('body,html').animate({scrollTop: $('#tab3').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(3).click(function(){
    $('body,html').animate({scrollTop: $('#tab4').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(4).click(function(){
    $('body,html').animate({scrollTop: $('#tab5').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(5).click(function(){
    $('body,html').animate({scrollTop: $('#tab6').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(6).click(function(){
    $('body,html').animate({scrollTop: $('#tab7').offset().top-30+'px'}, 800);
    });
    $('.tabs ul li').eq(7).click(function(){
    $('body,html').animate({scrollTop: $('#tab8').offset().top-30+'px'}, 800);
    });

    6 条回复    2016-01-20 11:50:57 +08:00
    hippoboy
        1
    hippoboy  
       2016-01-20 10:51:01 +08:00
    确定长度之后递归或者遍历?
    wesley
        2
    wesley  
       2016-01-20 11:01:11 +08:00
    $('.tabs ul li').click(function(){
    $('body,html').animate({scrollTop: $('#tab'+($(this).index()+1)).offset().top-30+'px'}, 800);
    });
    sleepwater
        3
    sleepwater  
       2016-01-20 11:07:38 +08:00
    $('.tabs ul li').on('click', function() {
    $('body,html').animate({scrollTop: $('#tab' + ($(this).index() + 1)).offset().top - 30 + 'px'}, 800);
    });
    chairuosen
        4
    chairuosen  
       2016-01-20 11:12:49 +08:00
    这种东西应该把 target 写到 html 里,$('[click-target]').click(function(){ some code scroll to $( $(this).attr('click-target') ); })
    shiye515
        5
    shiye515  
       2016-01-20 11:48:37 +08:00 via Android
    如果维护这个项目的人连这个都不会优化了,那就放弃治疗吧,这肯定不是项目里最奇葩的代码
    Zzzzzzzzz
        6
    Zzzzzzzzz  
       2016-01-20 11:50:57 +08:00
    这段就应该直接写成事件委托的.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2496 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 563ms · UTC 14:26 · PVG 22:26 · LAX 07:26 · JFK 10:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.