初次尝试写简单的 js,请问下面这样的循环代码怎样精简/合并?

2015-03-04 01:56:49 +08:00
 70599

在#post-index的div里,有若干个a,想要给被点击的a加上名为current的class,同时删除其他a上名为current的class。

下面是我自己写的,可用,但是很冗长。
请问这样的循环代码如何精简/合并?

$("#post-index a:nth-child(1)").click(function() {
    $('*').removeClass('current')
    $('#post-index a:nth-child(1)').addClass('current')
} );

$("#post-index a:nth-child(3)").click(function() {
    $('*').removeClass('current')
    $('#post-index a:nth-child(3)').addClass('current')
} );

$("#post-index a:nth-child(5)").click(function() {
    $('*').removeClass('current')
    $('#post-index a:nth-child(5)').addClass('current')
} );

$("#post-index a:nth-child(7)").click(function() {
    $('*').removeClass('current')
    $('#post-index a:nth-child(7)').addClass('current')
} );
4239 次点击
所在节点    程序员
21 条回复
xuyongli
2015-03-04 20:11:25 +08:00
$("#post-index a").click(function() {
$('.current').removeClass('current')
$(this).addClass('current')
} );

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

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

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

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

© 2021 V2EX