将元素值与当前日期进行比较

Compare element value with current date

本文关键字:比较 当前日期 元素      更新时间:2023-09-26

我正在研究一个JavaScript函数,试图从span中获取值,并将该值与今天的date进行比较

逻辑是:

如果跨度日期超过 30 天,请将其背景颜色更改为绿色

如果跨度日期超过 60 天,请将其背景颜色更改为蓝色

如果跨度日期超过 90 天,请将其背景色更改为红色

我目前的跨度是:

<span class="awsome">02/04/2011</span>
var s =`$('.awsome span').text();`    
alert(s);

我想将其与:

var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();

我的问题是如何同时比较和更改颜色?

$(document).ready(function() {
    function parseDate(str) {
        var mdy = str.split('/')
        return new Date(mdy[2], mdy[0]-1, mdy[1]);
    }
    function daydiff(first, second) {
        return (second-first)/(1000*60*60*24);
    }
    var today = new Date();
    console.log(today);
    $('.awesome').each(function() {
		var newDate = parseDate($(this).html());
        console.log(newDate);
        var difference = Math.abs(daydiff(newDate, today));
        if (difference > 90) {
        	$(this).css('background-color', 'red');
        }
        else if (difference > 60) {
        	$(this).css('background-color', 'blue');
        }
        else if (difference > 30) {
        	$(this).css('background-color', 'green');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="awesome">02/04/2011</span>
<span class="awesome">02/04/2016</span>
<span class="awesome">02/04/2015</span>
<span class="awesome">09/04/2015</span>
<span class="awesome">10/04/2015</span>
<span class="awesome">11/04/2015</span>

由于您使用jquery,因此可以这样做来更改span的背景颜色:

$( ".awsome span" ).each(function() {
  var date = $(this).text();
  // Here you would do your date comparison, setting isToday to true if the date is equal to today
  if (isToday)
       $( this ).css( "background-color", "green" );
  else
       $( this ).css( "background-color", "red" );
});

VanillaJS:

var day = 24 * 60 * 60 * 1000;
var spans = document.querySelectorAll("span.awsome");
Array.prototype.forEach.call(spans, function(span) {
  var date = new Date(Date.parse(span.innerText));
  var days = (new Date().getTime() - date.getTime()) / day;
  if (days > 30) {
    span.style.backgroundColor = "#aaffaa";
  }
  if (days > 60) {
    span.style.backgroundColor = "#aaaaff";
  }
  if (days > 90) {
    span.style.backgroundColor = "#ffaaaa";
  }
});
span {
  padding: 5px;
}
<span class="awsome">02/04/2015</span>
<span class="awsome">07/03/2015</span>
<span class="awsome">07/25/2015</span>

或者如果你想坚持使用jQuery:

var day = 24 * 60 * 60 * 1000;
$("span.awsome").each(function() {
  var date = new Date(Date.parse(this.innerText));
  var days = (new Date().getTime() - date.getTime()) / day;
  if (days > 30) {
    $(this).css("background-color", "#aaffaa");
  }
  if (days > 60) {
    $(this).css("background-color", "#aaaaff");
  }
  if (days > 90) {
    $(this).css("background-color", "#ffaaaa");
  }
});
span {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="awsome">02/04/2015</span>
<span class="awsome">07/03/2015</span>
<span class="awsome">07/25/2015</span>

可以使用

new Date(s)<span>日期(相当于 2011 年 2 月 4 日(获取 Date 对象。使用您的var d = new Date(),您可以获得当前日期/时间。有了这两个,您可以使用d - s来查找当前日期在跨度中的日期之后的毫秒数。由于它以毫秒为单位,因此您需要除以 1000 * 60 * 60 * 24 并向下舍入以获得完整的天数。假设我们存储了var difference的差异。1000 将其转换为秒,60 转换为分钟,另外 60 转换为小时,最后 24 转换为天。由于您只想要完整的天数,因此您可以四舍五入,因为其他任何内容都无关紧要。

找到以天为单位的差异后,您可以使用jQuery的.css()函数通过以下方式更改颜色

.css("background-color", difference > 90 ? "red" : difference > 60 ? "blue" : difference > 30 ? "green" : "white")

?是三元运算符。首先,它检查是否difference > 90,如果是,则返回"red",否则返回:之后的内容。在这种情况下,我们之后还有另一个三元运算符,所以它一直运行,直到找到 true 的东西,否则它会返回 "white"因为如果最后一个语句的计算结果为 false,则返回该运算符。最后一种颜色将是默认颜色。

由于您有很多<span class="awesome">,因此您需要遍历它们并使用.each()为每个 .因此,您的完整代码将如下所示:

$(".awesome").each(function() {
    var s = new Date($(this).text()),
        d = new Date(),
        difference = <ath.round((d - s) / (1000 * 60 * 60 * 24));
    $(this).css("background-color", difference > 90 ? "red" : difference > 60 ? "blue" : difference > 30 ? "green" : "white")
});

有关示例,请参阅 http://codepen.io/anon/pen/epmvLZ。

我倾向于建议使用addClass()而不是css();更新类名而不是直接操作给定节点的CSS通常被认为是"更干净的",因为使用类名,添加或删除,意味着您不必跟踪已更改或更新的单个属性,并允许在(不可避免的(设计更新期间轻松重新样式。

也就是说,我建议:

// today's date:
var today = new Date(),
// 'empty' variables for use in
// the later loop:
    delta, spanDate;
// selecting the <span> elements with the class-name of
// 'awsome' (note that I've preserved the misspelling),
// and then using the addClass() method:
$('span.awsome').addClass(function (index, currentClasses) {
    // jQuery methods tend to 'internally' iterate over
    // the collections to which they're chained, inside
    // the anonymous function 'this' refers to the current
    // DOM-node held inside the jQuery object/collection
    // over which we're iterating.
    // here we find the date represented by the text within the
    // <span> element's; we retrieve the text with the
    // Node.textContent property, split that string on the '/'
    // characters to form an array, we reverse that array and
    // join the string back together using the '/' character,
    // in order to convert dd/mm/yyyy into yyyy/mm/dd:
    spanDate = new Date(this.textContent.split('/').reverse().join('/'));
    // subtracting the date held in the <span> from today's date,
    // dividing the results by '(1000 * 60 * 60 * 24)' (which gives
    // the number of milliseconds per day) to find out how many
    // days the two dates are apart:
    delta = (today - spanDate) / (1000 * 60 * 60 * 24);
    // if the difference is less than 31 days (because you
    // specified 'more than 30' in your description) we
    // return the class-name of 'white':
    if (delta < 31) {
        return 'white';
    // otherwise, if it's more than 30, and less than
    // 61 we return the class-name 'green':
    } else if (delta > 30 && delta < 61) {
        return 'green';
    // and so on:
    } else if (delta > 60 && delta < 91) {
        return 'blue';
    } else if (delta > 90) {
        return 'red';
    }
});

var today = new Date(),
  delta, spanDate;
$('span.awsome').addClass(function(index, spanNode) {
  spanDate = new Date(this.textContent.split('/').reverse().join('/'));
  delta = (today - spanDate) / (1000 * 60 * 60 * 24);
  if (delta < 31) {
    return 'white';
  } else if (delta > 30 && delta < 61) {
    return 'green';
  } else if (delta > 60 && delta < 91) {
    return 'blue';
  } else if (delta > 90) {
    return 'red';
  }
});
.white {
  background-color: white;
}
.green {
  background-color: limegreen;
}
.blue {
  background-color: aqua;
}
.red {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="awsome">03/09/2015</span>
<span class="awsome">03/08/2015</span>
<span class="awsome">03/07/2015</span>
<span class="awsome">03/06/2015</span>

外部 JS 小提琴演示。

引用:

  • JavaScript:
    • Array.prototype.join() .
    • Date()构造函数。
    • Node.textContent .
    • String.prototype.split() .
  • j查询:
    • addClass() .

您必须遍历所有跨度,然后更改颜色。 你可以使用 jQuery each(( 这样的东西应该可以工作:

 $('.awsome span').each(function() {
   //compare the dates and change color 
});