【问题标题】:jQuery- find in multiple elements specific class & add to the first, second different classesjQuery- 在多个元素特定类中查找并添加到第一个、第二个不同的类
【发布时间】:2013-05-18 02:16:12
【问题描述】:

我在 div 容器中有一些带有和不带图像的新闻文章。现在想为每篇没有图片的文章添加一个不同的类。如果有图片,图片用<div class="news-img-wrap"></div>包裹。没有图片的文章没有这个div。所以我试试这个

$('.news-list-view article .content-background').each(function () {
   if ($(this).find('.news-img-wrap').length) {
      $(this).addClass('colored-box-red ');



   } else {
      $(this).addClass('default-box');
   }
});

此代码适用于所有带有图像的文章获取额外的类。 我的问题是如何给每篇带有图像的文章一个不同的额外类“第一、第二、第三”

到目前为止我的例子。http://jsfiddle.net/b9JuT/

感谢您的帮助,抱歉我的英语不好。

【问题讨论】:

  • 您是要向每个包含一个元素的 div 添加三个类,还是向某些包含特定模式或顺序的元素的 div 添加不同的类?

标签: jquery each css-selectors


【解决方案1】:

您可以使用计数并通过在每次添加类时递增它来动态创建唯一类:

var classCount = 1;

$('.news-list-view article .content-background').each(function () {
if ($(this).find('.news-img-wrap').length) {
    $(this).addClass('colored-box-red ').addClass('img-' + classCount);
     classCount++;
} else {
    $(this).addClass('default-box');
}
});

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多