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

时间:2015-09-03 18:59:32

标签: javascript jquery html css

我正在尝试使用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();

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

6 个答案:

答案 0 :(得分:1)

由于你使用jquery,你可以这样做来改变你的跨度的背景颜色:

$( ".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" );
});

答案 1 :(得分:1)

您可以使用new Date(s)<span>日期(相当于2011年2月4日)获取日期对象。使用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,如果是,则返回“红色”,否则返回:之后的内容。在这种情况下,我们之后会有另一个三元运算符,所以它会继续运行,直到找到正确的值,否则返回"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

答案 2 :(得分:1)

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

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

答案 3 :(得分:1)

VanillaJS:

&#13;
&#13;
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";
  }
});
&#13;
span {
  padding: 5px;
}
&#13;
<span class="awsome">02/04/2015</span>
<span class="awsome">07/03/2015</span>
<span class="awsome">07/25/2015</span>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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");
  }
});
&#13;
span {
  padding: 5px;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 4 :(得分:1)

$(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>

答案 5 :(得分:1)

我倾向于建议使用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';
    }
});

&#13;
&#13;
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';
  }
});
&#13;
.white {
  background-color: white;
}
.green {
  background-color: limegreen;
}
.blue {
  background-color: aqua;
}
.red {
  background-color: red;
}
&#13;
<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>
&#13;
&#13;
&#13;

外部JS Fiddle demo

参考文献: