Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/432.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery查找类并将其存储为变量_Javascript_Jquery_Html - Fatal编程技术网

Javascript jQuery查找类并将其存储为变量

Javascript jQuery查找类并将其存储为变量,javascript,jquery,html,Javascript,Jquery,Html,我有两个,其中包含时间线年份-和所附年份的类 我试图找到带有年份的类,并将年份提取到一个变量中,以便将文本附加到div中 年 年 $(“[class*=”时间线年“])。每个(函数(){ 风险值年=$(本); var list=$(this.attr(“类”).split(“”); 对于(变量i=0;i

我有两个
,其中包含
时间线年份-
和所附年份的类

我试图找到带有年份的类,并将年份提取到一个变量中,以便将文本附加到
div


年
年
$(“[class*=”时间线年“])。每个(函数(){
风险值年=$(本);
var list=$(this.attr(“类”).split(“”);
对于(变量i=0;i
$(“[class*=”时间线年“])。每个(函数(){
风险值年=$(本);
var list=$(this.attr(“类”).split(“”);
对于(变量i=0;i
使用
text
方法和一点常规支出的方法之一:

$('[class*="timeline-year"]').text(function () {
    return $(this).text() + ' ' + this.className.match(/timeline-year-(\d+)?/)[1];
});
演示: 但如果您使用以下方法,您的代码会更干净:

<div class="jsn-bootstrap3 timeline-events" data-year="2012">Year</div>
<div class="jsn-bootstrap3 timeline-events" data-year="2011">Year</div>
或仅使用CSS的事件在此情况下:

.timeline-events:after {
    content: ' ' attr(data-year);
}

CSS演示:使用
text
方法和一点常规体验的方法之一:

$('[class*="timeline-year"]').text(function () {
    return $(this).text() + ' ' + this.className.match(/timeline-year-(\d+)?/)[1];
});
演示: 但如果您使用以下方法,您的代码会更干净:

<div class="jsn-bootstrap3 timeline-events" data-year="2012">Year</div>
<div class="jsn-bootstrap3 timeline-events" data-year="2011">Year</div>
或仅使用CSS的事件在此情况下:

.timeline-events:after {
    content: ' ' attr(data-year);
}

CSS演示:另一种方法:获取class属性的内容,然后获取该字符串的最后4个字符:


另一种方法是:获取class属性的内容,然后获取该字符串的最后4个字符


假设您希望将年份文本从类属性中删除

$('[class*="timeline-year"]').each(function(){
    var classString = $(this).attr('class');
    var year = classString.match(/\d+$/)[0];
    console.log(year);
});
演示:


假设您希望将年份文本从类属性中删除

$('[class*="timeline-year"]').each(function(){
    var classString = $(this).attr('class');
    var year = classString.match(/\d+$/)[0];
    console.log(year);
});
演示:


(在数据之前关闭类属性)这将是一个很好的使用方法,不幸的是,
数据年
无法设置,目前只能作为类使用。但答案很好!(在数据之前关闭类属性)这将是一个很好的使用方法,不幸的是,
数据年
无法设置,目前只能作为类使用。但答案很好!