每个元素的Jquery长度具有相同的类

时间:2015-09-29 18:04:07

标签: jquery

我有不同数量的div与类“news-list-view-2-cols”。它们包含不同数量的div和类“article”。我想说一个“div class news-list-view-2-cols”中的“div class article”的数量是大于等于2,然后将addClass“article-last”添加到父元素的最后两个div中。

我正在尝试

if ($( ".news-list-view-2-cols .article" ).length >= 2) { 
    $( ".news-list-view-2-cols .article").slice(-2).addClass("article-last");
}

这适用于html代码中的最后一个“news-list-view-2-cols”,但不适用于之前的版本。所以我必须找到一个解决方案,它给出了每个(.news-list-view-2-cols .article)长度的数量。我试过,但没有成功。

实例:

if ($( ".news-list-view-2-cols .article" ).length >= 2) { 
    $( ".news-list-view-2-cols .article").slice(-2).addClass("article-last");
}

/*
$( ".news-list-view-2-cols .article" ).each(function() {
    if ( this.length >= 2 ) {
        this.slice(-2).addClass("article-last")
	}
});
*/
.news-list-view-2-cols {
    border-bottom: 1px solid #CCC;
}
.article-last {
    color: red
}
<div class="news">
	<div class="news-list-view-2-cols cf">
		<div class="article articletype-0">1</div>
		<div class="article articletype-0">2</div>
	</div>
</div>

<div class="news">
	<div class="news-list-view-2-cols cf">
		<div class="article articletype-0">1</div>
		<div class="article articletype-0">2</div>
		<div class="article articletype-0">3</div>
		<div class="article articletype-0">4</div>
	</div>
</div>

<div class="news">
	<div class="news-list-view-2-cols cf">
		<div class="article articletype-0">1</div>
		<div class="article articletype-0">2</div>
		<div class="article articletype-0">3</div>
		<div class="article articletype-0">4</div>
	</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Fiddle

1 个答案:

答案 0 :(得分:0)

您需要仅剪切文章集,而不是整体集:

$( ".news-list-view-2-cols").each(function() {
    var articles = $(this).find(".article");
    if (articles.length >= 2) { 
        articles.slice(-2).addClass("article-last");
    }
});

直播示例:

&#13;
&#13;
$(".news-list-view-2-cols").each(function() {
  var articles = $(this).find(".article");
  if (articles.length >= 2) {
    articles.slice(-2).addClass("article-last");
  }
});
&#13;
.news-list-view-2-cols {
  border-bottom: 1px solid #CCC;
}
.article-last {
  color: red
}
&#13;
<div class="news">
  <div class="news-list-view-2-cols cf">
    <div class="article articletype-0">1</div>
    <div class="article articletype-0">2</div>
  </div>
</div>

<div class="news">
  <div class="news-list-view-2-cols cf">
    <div class="article articletype-0">1</div>
    <div class="article articletype-0">2</div>
    <div class="article articletype-0">3</div>
    <div class="article articletype-0">4</div>
  </div>
</div>

<div class="news">
  <div class="news-list-view-2-cols cf">
    <div class="article articletype-0">1</div>
    <div class="article articletype-0">2</div>
    <div class="article articletype-0">3</div>
    <div class="article articletype-0">4</div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
&#13;
&#13;
&#13;