初次尝试写简单的 js,请问下面这样的循环代码怎样精简/合并? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
请不要在回答技术问题时复制粘贴 AI 生成的内容
70599
V2EX    程序员

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

  •  
  •   70599 2015-03-04 01:56:49 +08:00 4647 次点击
    这是一个创建于 3882 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在#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') } ); 
    21 条回复    2015-03-04 20:11:25 +08:00
    blacktulip
        1
    blacktulip  
       2015-03-04 02:11:07 +08:00
    loop through 每个 a , 给加上 同一个 event listener ,listener 里面用 target 判断是哪个 a 被点击
    shuding
        2
    shuding  
       2015-03-04 02:20:40 +08:00
    直接化简的话是:

    https://gist.github.com/quietshu/c2c892816b3169367e31

    不过感觉你的需求第二行不应该写 `$('*')`,这样效率好低的……
    yyfearth
        3
    yyfearth  
       2015-03-04 02:21:32 +08:00   1
    @blacktulip 应该用delegation绑定在#post-index 而不是给每个a绑定
    然后listener 里面用 this 判断是哪个 a 被点击

    另外 $('*') 不要随便用 这样可是选择所有元素啊 效率很低的
    你可以用 $('a.current').removeClass('current') 来缩小范围
    而且后面那个添加class的 可以直接用 $(this).addClass('current')
    blacktulip
        4
    blacktulip  
       2015-03-04 02:24:18 +08:00
    我只会写一点 Vanilla Javascript ,你自己翻译成 jQuery 吧...

    <p id="post-index">
    <a class="current" href="#">link 1</a>
    <a href="#">link 2</a>
    <a href="#">link 3</a>
    </p>

    <script>
    var links = document.querySelectorAll("a");
    for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("click", function(event) {
    for (var j = 0; j < links.length; j++) {
    links[j].className = "";
    }
    event.target.className = "current";
    });
    }

    </script>
    cevincheung
        5
    cevincheung  
       2015-03-04 02:25:21 +08:00
    siblings
    blacktulip
        6
    blacktulip  
       2015-03-04 02:26:47 +08:00
    @yyfearth 噢,确实如此,thanks
    EthanZ
        7
    EthanZ  
       2015-03-04 06:40:10 +08:00
    Can't type Chinese.

    Are you trying to implement a ratio button? If not, make a function to clear all "current" class, and add new class on 'click' in another function, in this case it's more flexible.

    function clearCurrent() {$('.current').removeClass('current')}
    $('#post-index a').on('click', function() {$(this).addClass('current')}

    or use trigger, depends on your requirement.

    You should really post your requirement(like implement multiselect in js), then we may provide you a more efficient solution.
    ricorico
        8
    ricorico  
       2015-03-04 07:31:09 +08:00 via iPad
    Google 一下事件委托
    FastMem
        9
    FastMem  
       2015-03-04 09:32:29 +08:00
    直接用this嘛,你这样好麻烦的!

    $(".post-index a").click(function() {
    $(this).addClass('current');
    $(this).siblings().removeClass('current');
    });

    不知道符不符合,这个是删除同级a元素。
    arachide
        10
    arachide  
       2015-03-04 09:39:12 +08:00
    你这个时jquery化的js
    很容易把js搞成一坨屎
    bzw875
        11
    bzw875  
       2015-03-04 09:41:26 +08:00
    $("#post-index a").click(function(e){
    $("#post-index a").removeClass('current');
    $(e.target).addClass('current');
    });
    muzuiget
        12
    muzuiget  
       2015-03-04 10:27:22 +08:00
    用 siblings() 就行了,再加上链式调用,一行就搞定了。

    $('#post-index a').click(function() {
    $(this).addClass('current').siblings().removeClass('current');
    });
    sm0king
        13
    sm0king  
       2015-03-04 10:30:08 +08:00
    @FastMem 我赞同这种写法。但他貌似是要选择 #post-index 下奇数的a 所以用 $("#post-index a:nth-child(Odd)") 吧?
    shuson
        14
    shuson  
       2015-03-04 10:35:03 +08:00
    献丑一个:
    $('#post-index a').click(function(event){
    event.preventDefault();
    $(this).addClass('current')
    $(this).siblings().removeClass('current');
    });
    exceloo
        15
    exceloo  
       2015-03-04 10:48:57 +08:00
    siblings就可搞定,上面已经有人提供代码了
    serenader
        16
    serenader  
       2015-03-04 11:06:11 +08:00
    http://codepen.io/anon/pen/OPwjJZ

    不知道楼主是不是要这种效果。
    asd234ddd
        17
    asd234ddd  
       2015-03-04 11:27:25 +08:00 via Android
    小白想问php代码哪个地方写。。
    unknownservice
        18
    unknownservice  
       2015-03-04 15:13:47 +08:00
    @sm0king nth-child()这是css了,jquery用$("#post-index a:odd")就行了。
    FastMem
        19
    FastMem  
       2015-03-04 16:04:09 +08:00
    @unknownservice 我记得好像他那样写也是可以的,因为之前有个大神告诉我CSS的选择器 = JQ的选择器。不过我没试验过!
    unknownservice
        20
    unknownservice  
       2015-03-04 16:29:36 +08:00
    @FastMem 可以这么写,类似的还有eq()选择器,不过我是强迫症,能短点更好:)
    说是完全想等倒也不是,JQ应该更多点,类似gt() lt() not这样的。
    xuyongli
        21
    xuyongli  
       2015-03-04 20:11:25 +08:00
    $("#post-index a").click(function() {
    $('.current').removeClass('current')
    $(this).addClass('current')
    } );
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     2654 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 23ms UTC 03:14 PVG 11:14 LAX 20:14 JFK 23:14
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86