jQuery从Date提取年份并将类添加到Parent

我正在寻找为div列表创建一个同位素filter,因此想要通过从显示的日期中提取’Year’然后将其作为类添加到父容器/ div来添加一年的类到父容器/ div div( .publication

现在我正在使用一种非常基本的方法来查看div是否包含特定年份然后单独指定一年:

HTML

 
15/3/2017
15/3/2016

 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年以上,则不会分配任何课程。 如果我们可以爆炸日期并提取课程的年份,那么这将继续逐年进行?

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

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

工作小提琴

编辑:在评论中回答OP问题:

使用replace以’ – ‘替换所有空格,并将结果添加到.publication的类中。

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

您可以遍历每个元素并拆分文本。

而且你不需要使用.closest()但只需使用.parent()

更新。 由于您的代码位于您网站上的示例中。 你必须使用最接近的网站代码。 更新了html以匹配您的网站HTML。

 jQuery('div[class*="publication-date"]').each(function() { var year = $(this).text().split("/"); $(this).closest(".publication").addClass(year[year.length - 1]); }); 
  

Cosmética

Sur
15/3/2017