如何使用Jquery隐藏最后3个div

时间:2015-06-16 21:27:15

标签: javascript jquery css

到目前为止,我尝试使用JQuery选择最后3个div。但它似乎不起作用

$(document).ready(function(){

  $( "div.span4:nth-child(6), div.span4:nth-child(7), div.span4:nth-child(8)" ).
    addClass( "myClass" );

});
<div class="row-fluid">

  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>
  <div class="span4"></div>

</div>

5 个答案:

答案 0 :(得分:7)

试试这个:

$('.span4:gt(-4)').hide();
// It's simply "greater than fourth one from the end" ;)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<div class="row-fluid">

  <div class="span4">1</div>
  <div class="span4">2</div>
  <div class="span4">3</div>
  <div class="span4">4</div>
  <div class="span4">5</div>
  <div class="span4">6</div>
  <div class="span4">7</div>
  <div class="span4">8</div>

</div>

答案 1 :(得分:2)

似乎使用nth-child():http://jsfiddle.net/3b8su8f4/

$(document).ready(function(){
    $( "div.span4:nth-child(6),div.span4:nth-child(7),div.span4:nth-child(8) " ).addClass( "myClass" );
});

答案 2 :(得分:1)

使用:gt()选择器

var divLength = $('div.span4').length;
$('div.span4:gt(' + (divLength - 4) + ')').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row-fluid">

  <div class="span4">1</div>
  <div class="span4">2</div>
  <div class="span4">3</div>
  <div class="span4">4</div>
  <div class="span4">5</div>
  <div class="span4">6</div>
  <div class="span4">7</div>
  <div class="span4">8</div>

</div>

答案 3 :(得分:1)

您可以使用:

$('div.span4').slice(-3).addClass('myClass');

jsfiddle

答案 4 :(得分:1)

nth-last-child应该做什么?

$('div.span4:nth-last-child(-n+3)').addClass('myClass');
.span4 {
  background: #666;
}

.myClass {
  background: #0cc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="row-fluid">
  <div class="span4">1</div>
  <div class="span4">2</div>
  <div class="span4">3</div>
  <div class="span4">4</div>
  <div class="span4">5</div>
  <div class="span4">6</div>
  <div class="span4">7</div>
  <div class="span4">8</div>
</div>