jQuery从日期中提取年份并将类添加到父级 [英] jQuery Extract Year from Date and Add Class to Parent

查看:119
本文介绍了jQuery从日期中提取年份并将类添加到父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为div列表创建一个同位素过滤器,因此想通过从显示的日期中提取年份",然后将其添加为类来将年份的类添加到父容器/div中到父div(.publication)

I'm looking to create an isotope filter to a div list and as such want to add a class of the year to a parent container/div by extracting the 'Year' from a displayed date and then adding that as the class to the parent div (.publication)

现在,我正在使用一种非常基本的方法来执行此操作,方法是查看div是否包含特定年份,然后分别分配年份:

Right now I am using a very basic method to do this by looking to see if a div contains a specific year and then individually assigning a year:

HTML

<div>
  <div class="publication addyearclasshere">
  <div class="publication-date">15/3/2017</div>
</div>

<div class="publication addyearclasshere">
  <div class="publication-date">15/3/2016</div>
</div>

代码

jQuery('div[class*="publication-date"]:contains("2020")').closest('.publication').addClass('2020');
jQuery('div[class*="publication-date"]:contains("2019")').closest('.publication').addClass('2019');
jQuery('div[class*="publication-date"]:contains("2018")').closest('.publication').addClass('2018');
jQuery('div[class*="publication-date"]:contains("2017")').closest('.publication').addClass('2017');
jQuery('div[class*="publication-date"]:contains("2016")').closest('.publication').addClass('2016');
jQuery('div[class*="publication-date"]:contains("2015")').closest('.publication').addClass('2015');

这种方法的问题是,如果我们低于2015年或高于2020年,则不会分配任何课程.如果我们可以分解日期并提取班级的年份,那么这将逐年延续吗?

The problem with this approach is that if we go below 2015 or above 2020 no class is assigned. If we can explode the date and extract the year for the class then this would keep going year on year?

推荐答案

遍历每个.publication-date并从其文本中提取年份.将年份作为类添加到其父级.像这样:

Loop through each .publication-date and extract the year from its text. Add the year as a class to its parent. Like this:

jQuery(".publication-date").each(function(i) {
    var yr = $(this).text().trim().split('/')[2];
    jQuery(this).closest('.publication').addClass(yr);
});

工作小提琴

要在评论中回答OP的问题,

To answer the OPs question in the comments:

使用replace用'-'替换所有空格,并将结果添加到.publication的类中.

Use replace to replace all the spaces by '-' and add the result to .publication's class.

jQuery(".publication-name").each(function(i) {
    var name = $(this).text().trim().replace(' ', '-');
    jQuery(this).closest('.publication').addClass(name);
});

这篇关于jQuery从日期中提取年份并将类添加到父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆