【问题标题】:nth-child and if else statementnth-child 和 if else 语句
【发布时间】:2012-12-18 15:46:22
【问题描述】:

是否可以使用 nth-child 和 if else 语句来实现以下目标?

假设有 9 个 div,每个 div 内部都有一个链接,单击该链接会执行一项功能。我可以让链接找出它在里面的第n个子div(来自body标签),并且只有当它在第3、第6或第9个div内时才执行该功能?我真的不知道从哪里开始,但似乎有可能。

【问题讨论】:

    标签: javascript jquery if-statement css-selectors


    【解决方案1】:

    你可以使用nth-clild

    Live Demo

    $('.divclass :nth-child(3n)')
    

    绑定事件可以使用click()

    Live demo

    $('#divId div:nth-child(3n) a').click(function(){
      alert($(this).text());    
    });​
    

    【讨论】:

      【解决方案2】:

      jsBin demo

      $('div:nth-child(3n)').find('a').click(function( e ){
      
        e.preventDefault();
      
        alert( $(this).text() );
      
      });
      

      【讨论】:

        【解决方案3】:
        $('divclass:nth-child(3n)').find('a').on('click',function(){
            alert( $(this).text() );
        });
        

        希望这可行 :) 干杯

        【讨论】:

        • live 方法已弃用,所以我认为这不是建议答案的好方法
        • 是的@roXon,现在不推荐使用 Live 了。但是我们可以使用 .on()
        • 像这样 $('divclass:nth-child(3n)').find('a').on('click',function(){ alert( $(this).text( ) ); });
        • 编辑了你的答案,虽然我真的不知道在哪里特别提到需要使用.on() ...
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-11
        • 1970-01-01
        • 2014-02-15
        • 2019-04-09
        • 1970-01-01
        相关资源
        最近更新 更多