JQuery nth-child工作不正常

Kei*_*gan 8 jquery css-selectors

我正在使用JQuery的nth-child选择器用photo_post_thumbnail类改变每个第3个div上的边距,但它每隔2个div改变一次?

谁能发现我做错了什么?

现场

http://www.clients.eirestudio.net/hatstand/wordpress/photos/

HTML标记

<div class="postbox photo_post_thumbnail">
      blah blah
</div>

<div class="postbox photo_post_thumbnail">
      blah blah
</div>

<div class="postbox photo_post_thumbnail">
      blah blah
</div>
Run Code Online (Sandbox Code Playgroud)

JQuery代码

$('.photo_post_thumbnail:nth-child(3n)').css('margin-right', '0px');
Run Code Online (Sandbox Code Playgroud)

Nic*_*ver 12

它是这样做的,因为你有一个<h1>在这些div之前,使div成为第四个孩子而不是第三个:)

nth-child选择是起初有点混乱,因为它的nth-child 母公司,而不仅仅是nth-child 该选择匹配父,选择无轴承此选择的位置.

要获得您想要的div,请执行3n+1以下操作:

$('.photo_post_thumbnail:nth-child(3n+1)').css('margin-right', '0px');
Run Code Online (Sandbox Code Playgroud)


ant*_*ant 5

替代方案:

   $('.photo_post_thumbnail').each(function(i) {
      i=(i+1);
      if(i%3==0){
     $(this).css("margin-right","0px"));
    }
   });
Run Code Online (Sandbox Code Playgroud)