nth-child和if else声明

时间:2012-12-18 05:49:25

标签: javascript jquery if-statement css-selectors

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

假设有9个div,每个div都有一个链接,当点击时执行一个功能。我可以以某种方式让链接找出它所在的nth-child div(来自body标签)并且仅当它在第3,第6或第9个div内时执行该功能?我真的不知道从哪里开始,但似乎有可能。

3 个答案:

答案 0 :(得分:4)

您可以使用nth-clild

<强> Live Demo

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

对于绑定事件,您可以使用click()

<强> Live demo

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

答案 1 :(得分:2)

jsBin demo

$('div:nth-child(3n)').find('a').click(function( e ){

  e.preventDefault();

  alert( $(this).text() );

});

答案 2 :(得分:0)

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

希望这有效:)干杯