问题描述
这是原始问题的扩展:
This is an extension of original question: jQuery Extract Year from Date and Add Class to Parent
...但我需要对其进行扩展,以便合并2个现有函数,然后将其扩展为添加数组中的属性而不是类。
... but I need to extend it so that the 2 existing functions are combined and then extended to add an attribute in an array rather than a class.
将类值增加的原始代码段: -
从div获取日期并添加为类
Gets date from div and add as class
jQuery(".publication-date").each(function(i) {
var yr = $(this).text().trim().split('/')[2];
jQuery(this).closest('.publication').addClass(yr);
});
从div获取发布名称并添加为类
Gets publication name from div and add as class
jQuery(".publication-name").each(function(i) {
var name = $(this).text().trim().replace(/[_\W]+/g, "-");
jQuery(this) .closest('。publication')。addClass(name);
});
jQuery(this).closest('.publication').addClass(name); });
我努力合并并写入'数据属性' -filter'其中data-filter有任何以逗号分隔的值,即。 data-filter2017,publicationname
$(".publication-date, .publication-name").each(function(i) {
var yr = $('.publication-date').text().trim().split('/')[2];
var name = $('.publication-name').text().trim().replace(/[_\W]+/g, "-");
value = yr + ',' + name;
$(this).closest('.publication').attr({
"data-filter": value
});
});
所有输入都非常感谢。
谢谢提前
Glennyboy
Glennyboy
推荐答案
假设在您的HTML中,每个 .publication
div
都有一个 .publicaton-date
div
和一个刊物名称
div
,你可以做一些事情:
Assuming that, in your HTML, each of your .publication
div
has one .publicaton-date
div
and one publication-name
div
, you can do something on the lines of:
$('.publication').each(function() {
var yr = $(this).find('.publication-date').text().trim().split('/')[2];
var name = $(this).find('.publication-name').text().trim().replace(/[_\W]+/g, "-");
$(this).attr('data-filter', yr + ',' + name);
})
ie:而不是循环 .publication-date
和 .publication-name
元素,遍历 .publication
元素并在其中查找日期和年份。
ie: Instead of looping through the .publication-date
and .publication-name
elements, loop through the .publication
elements and find the date and year inside them.
这篇关于在jQuery或Javascript中组合2个函数写入属性数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!