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

2016-01-20 10:11:07 +08:00
 zebulon

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

2164 次点击
所在节点    问与答
6 条回复
hippoboy
2016-01-20 10:51:01 +08:00
确定长度之后递归或者遍历?
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
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
2016-01-20 11:12:49 +08:00
这种东西应该把 target 写到 html 里,$('[click-target]').click(function(){ some code scroll to $( $(this).attr('click-target') ); })
shiye515
2016-01-20 11:48:37 +08:00
如果维护这个项目的人连这个都不会优化了,那就放弃治疗吧,这肯定不是项目里最奇葩的代码
Zzzzzzzzz
2016-01-20 11:50:57 +08:00
这段就应该直接写成事件委托的.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/252008

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX